Skip to content

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

fix(perf): eliminate recording-time CPU regressions and heal GPU-pack fallout (#1863)

Gabriel Stein600d65af0ded
diff --git a/main.js b/main.js
index e2b5b1657..366d12ca4 100644
--- a/main.js
+++ b/main.js
@@ -284,7 +284,8 @@ const TextEditMonitor = require("./src/helpers/textEditMonitor");
const SelectionManager = require("./src/helpers/selectionManager");
const WhisperCudaManager = require("./src/helpers/whisperCudaManager");
const WhisperVulkanManager = require("./src/helpers/whisperVulkanManager");
-const { migrateLegacyBinDir } = require("./src/helpers/gpuBinaryManager");
+const { migrateLegacyBinDir, detectOrphanedGpuPacks } = require("./src/helpers/gpuBinaryManager");
+const { resetWhisperGpuFailureOnUpgrade } = require("./src/helpers/whisperGpuUpgradeReset");
const GoogleCalendarManager = require("./src/helpers/googleCalendarManager");
const MicrosoftCalendarManager = require("./src/helpers/microsoftCalendarManager");
const AppleCalendarManager = require("./src/helpers/appleCalendarManager");
@@ -438,16 +439,29 @@ function initializeCoreManagers() {
// Heal installs from before GPU packs got per-pack directories; must run
// before startup pre-warm resolves any GPU binary path.
const LlamaVulkanManager = require("./src/helpers/llamaVulkanManager");
+ const llamaVulkanManager = new LlamaVulkanManager();
const clearedPacks = migrateLegacyBinDir([
whisperCudaManager,
whisperVulkanManager,
- new LlamaVulkanManager(),
+ llamaVulkanManager,
]);
if (clearedPacks.length > 0) {
// No window exists yet — persist the notice; a control panel window
// shows it as a toast and clears it. See #1606.
require("./src/helpers/gpuPackMigrationNotice").record(clearedPacks);
}
+ // The 1.8.3 migration deleted lib-carrying packs without recording that
+ // notice, leaving those users on a silent CPU fallback: an enabled flag
+ // with no pack on disk only happens via such data loss. recordOnce gates
+ // each pack to one notice so a dismissed toast doesn't return every launch.
+ const orphanedPacks = detectOrphanedGpuPacks([
+ { manager: whisperCudaManager, enabledEnvVar: "WHISPER_CUDA_ENABLED" },
+ { manager: whisperVulkanManager, enabledEnvVar: "WHISPER_VULKAN_ENABLED" },
+ { manager: llamaVulkanManager, enabledEnvVar: "LLAMA_VULKAN_ENABLED" },
+ ]);
+ if (orphanedPacks.length > 0) {
+ require("./src/helpers/gpuPackMigrationNotice").recordOnce(orphanedPacks);
+ }
// Lets every server start resolve its GPU backend from installed packs
whisperManager.setGpuBinaryManagers({ cuda: whisperCudaManager, vulkan: whisperVulkanManager });
}
@@ -961,6 +975,9 @@ async function startApp() {
// Phase 1: Core managers + IPC handlers before windows
initializeCoreManagers();
await environmentManager.init();
+ // After any upgrade the GPU gets one fresh attempt: clear the remembered
+ // failure before the whisper pre-warm below resolves its GPU backend.
+ resetWhisperGpuFailureOnUpgrade(environmentManager);
registerSidecars();
startAuthBridgeServer();
@@ -1228,23 +1245,30 @@ async function startApp() {
const QdrantManager = require("./src/helpers/qdrantManager");
qdrantManager = new QdrantManager();
+ // Must not throw: this also runs inside the unhealthy-restart path, whose
+ // catch would stop the replacement sidecar.
+ const wireVectorIndex = (port) => {
+ try {
+ const vectorIndex = require("./src/helpers/vectorIndex");
+ vectorIndex.init(port);
+ vectorIndex
+ .ensureCollection()
+ .then(() => ipcHandlers?.drainPendingVectorPurges())
+ .catch((err) => {
+ debugLogger.debug("Qdrant collection setup error (non-fatal)", { error: err.message });
+ });
+ } catch (err) {
+ debugLogger.debug("Qdrant rewire error (non-fatal)", { error: err.message });
+ }
+ };
+ // A successful unhealthy-restart can bring the sidecar back on a new port.
+ qdrantManager.on("restarted", wireVectorIndex);
sidecarRegistry.register("qdrant", () => qdrantManager.stop());
if (qdrantManager.isAvailable()) {
qdrantManager
.start()
.then(() => {
- if (qdrantManager.isReady()) {
- const vectorIndex = require("./src/helpers/vectorIndex");
- vectorIndex.init(qdrantManager.getPort());
- vectorIndex
- .ensureCollection()
- .then(() => ipcHandlers?.drainPendingVectorPurges())
- .catch((err) => {
- debugLogger.debug("Qdrant collection setup error (non-fatal)", {
- error: err.message,
- });
- });
- }
+ if (qdrantManager.isReady()) wireVectorIndex(qdrantManager.getPort());
})
.catch((err) => {
debugLogger.debug("Qdrant startup error (non-fatal)", { error: err.message });
diff --git a/src/components/notes/MeetingTranscriptChat.tsx b/src/components/notes/MeetingTranscriptChat.tsx
index 5b726c910..92fc9b600 100644
--- a/src/components/notes/MeetingTranscriptChat.tsx
+++ b/src/components/notes/MeetingTranscriptChat.tsx
@@ -1,5 +1,6 @@
-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
+import { memo, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
+import { useVirtualizer } from "@tanstack/react-virtual";
import { Check, Loader2, ShieldCheck, Sparkles, Users, X } from "lucide-react";
import { Popover, PopoverTrigger, PopoverContent } from "../ui/popover";
import { Toggle } from "../ui/toggle";
@@ -50,6 +51,11 @@ const SPEAKER_BORDER_COLORS = [
];
const STICKY_SCROLL_THRESHOLD_PX = 80;
+// One unlabelled line of transcript; measureElement corrects each row on mount.
+const ESTIMATED_ROW_PX = 56;
+// Renders a screenful before the scroll element has been measured, instead of
+// an empty list for one frame. Replaced by the real rect on mount.
+const INITIAL_VIEWPORT_RECT = { width: 400, height: 600 };
const getEffectiveSpeakerKey = (
segment: TranscriptSegment,
@@ -557,6 +563,144 @@ export function SelectionBar({
);
}
+interface SegmentRowProps {
+ segment: TranscriptSegment;
+ selfSide: boolean;
+ sameSpeaker: boolean;
+ isFirst: boolean;
+ isNewest: boolean;
+ colorIdx: number;
+ isSelected: boolean;
+ activeName?: string;
+ matchedProfile?: SpeakerProfileLite;
+ speakerProfiles?: SpeakerProfileLite[];
+ participants?: Array<{ email: string; displayName: string | null }>;
+ onMapSpeaker?: (
+ speakerId: string,
+ displayName: string,
+ email?: string | null,
+ profileId?: number
+ ) => void;
+ onConfirmSuggestion?: (speakerId: string, suggestedName: string, profileId: number) => void;
+ onDismissSuggestion?: (speakerId: string) => void;
+ onAttachSpeakerEmail?: (profileId: number, email: string | null) => void;
+ onToggleSelect?: (segmentId: string) => void;
+ t: (key: string, opts?: Record<string, unknown>) => string;
+}
+
+// Memoized so live partials (several per second) only re-render the two partial
+// bubbles, not every settled row. Everything a row displays arrives as a prop
+// whose identity/value only changes when that row's rendering changes. Only the
+// arriving row animates in: a virtualized row remounts whenever it scrolls back
+// into view, so older rows would replay their entrance.
+const SegmentRow = memo(function SegmentRow({
+ segment,
+ selfSide,
+ sameSpeaker,
+ isFirst,
+ isNewest,
+ colorIdx,
+ isSelected,
+ activeName,
+ matchedProfile,
+ speakerProfiles,
+ participants,
+ onMapSpeaker,
+ onConfirmSuggestion,
+ onDismissSuggestion,
+ onAttachSpeakerEmail,
+ onToggleSelect,
+ t,
+}: SegmentRowProps) {
+ const hasSpeaker = !!segment.speaker;
+ const isOriginallyYou = segment.speaker === "you";
+ const isSystemSpeaker = hasSpeaker && !selfSide;
+ const selectable = !!onToggleSelect;
+
+ const canAddContact =
+ !!matchedProfile &&
+ matchedProfile.id != null &&
+ !matchedProfile.email &&
+ !!onAttachSpeakerEmail;
+
+ const labelElement = hasSpeaker && (
+ <div className="flex items-center gap-1">
+ <SpeakerLabel
+ speakerId={segment.speaker!}
+ segment={segment}
+ resolvedName={activeName}
+ speakerProfiles={speakerProfiles}
+ participants={participants}
+ colorIdx={colorIdx}
+ isOriginallyYou={isOriginallyYou}
+ onMap={onMapSpeaker}
+ onConfirm={onConfirmSuggestion}
+ onDismiss={onDismissSuggestion}
+ t={t}
+ />
+ {canAddContact && matchedProfile && matchedProfile.id != null && (
+ <AddContactButton
+ profile={{ id: matchedProfile.id, display_name: matchedProfile.display_name }}
+ onAttachEmail={onAttachSpeakerEmail!}
+ t={t}
+ />
+ )}
+ </div>
+ );
+
+ return (
+ <div
+ className={cn(
+ "group flex flex-col",
+ selfSide ? "items-start" : "items-end",
+ !sameSpeaker && !isFirst && "mt-2",
+ selectable && (selfSide ? "pl-6" : "pr-6")
+ )}
+ style={isNewest ? { animation: "agent-message-in 200ms ease-out both" } : undefined}
+ >
+ {labelElement && !sameSpeaker && labelElement}
+ {labelElement && sameSpeaker && (
+ <div
+ className={cn(
+ "grid grid-rows-[0fr] opacity-0 pointer-events-none transition-[grid-template-rows,opacity] duration-150 ease-out",
+ "group-hover:grid-rows-[1fr] group-hover:opacity-100 group-hover:pointer-events-auto"
+ )}
+ >
+ <div className="overflow-hidden">{labelElement}</div>
+ </div>
+ )}
+ <div className="relative max-w-[80%]">
+ <div
+ className={cn(
+ "px-3 py-1.5 cursor-default transition-colors",
+ "text-[13px] leading-relaxed",
+ selfSide
+ ? cn(
+ "bg-primary/90 text-primary-foreground",
+ sameSpeaker ? "rounded-lg rounded-tl-sm" : "rounded-lg rounded-bl-sm"
+ )
+ : cn(
+ "bg-surface-2 border border-border/30 text-foreground",
+ sameSpeaker ? "rounded-lg rounded-tr-sm" : "rounded-lg rounded-br-sm",
+ isSystemSpeaker && cn("border-l-2", SPEAKER_BORDER_COLORS[colorIdx])
+ ),
+ isSelected && "ring-2 ring-primary/60"
+ )}
+ >
+ {segment.text}
+ </div>
+ {selectable && (
+ <SelectCheckbox
+ isSelected={isSelected}
+ onToggle={() => onToggleSelect?.(segment.id)}
+ className={cn("absolute top-1.5", selfSide ? "-left-6" : "-right-6")}
+ />
+ )}
+ </div>
+ </div>
+ );
+});
+
interface MeetingTranscriptChatProps {
segments: TranscriptSegment[];
micPartial?: string;
@@ -613,6 +757,18 @@ export function MeetingTranscriptChat({
const scrollRef = useRef<HTMLDivElement>(null);
const shouldStickToBottomRef = useRef(true);
+ // Rows are keyed by segment id, not index: segments are inserted by timestamp
+ // and retracted mid-list, which would misalign an index-keyed size cache.
+ const virtualizer = useVirtualizer({
+ count: segments.length,
+ getScrollElement: () => scrollRef.current,
+ estimateSize: () => ESTIMATED_ROW_PX,
+ getItemKey: (index) => segments[index].id,
+ initialRect: INITIAL_VIEWPORT_RECT,
+ overscan: 8,
+ });
+ const totalSize = virtualizer.getTotalSize();
+
useEffect(() => {
const el = scrollRef.current;
if (!el) return;
@@ -630,7 +786,7 @@ export function MeetingTranscriptChat({
const el = scrollRef.current;
if (!el || !shouldStickToBottomRef.current) return;
el.scrollTop = el.scrollHeight;
- }, [segments, micPartial, systemPartial]);
+ }, [segments, micPartial, systemPartial, totalSize]);
const hasContent = segments.length > 0 || micPartial || systemPartial;
const systemPartialSpeakerLabel =
@@ -644,20 +800,42 @@ export function MeetingTranscriptChat({
: "provisional"
: undefined;
+ // Per-segment derivations hoisted out of the row map: rows receive them as
+ // stable props, so partial ticks (which change neither input) skip every row.
+ const rowMeta = useMemo(
+ () =>
+ segments.map((segment) => ({
+ key: getEffectiveSpeakerKey(segment, speakerMappings),
+ activeName: resolveSegmentSpeakerName(segment, speakerMappings),
+ })),
+ [segments, speakerMappings]
+ );
+
const colorByKey = useMemo(() => {
const map = new Map<string, number>();
let nextIdx = 0;
- for (const segment of segments) {
- if (segment.source === "mic" && !segment.speaker) continue;
- if (segment.speaker === "you") continue;
- const key = getEffectiveSpeakerKey(segment, speakerMappings);
+ segments.forEach((segment, i) => {
+ if (segment.source === "mic" && !segment.speaker) return;
+ if (segment.speaker === "you") return;
+ const key = rowMeta[i].key;
if (!map.has(key)) {
map.set(key, nextIdx % SPEAKER_COLORS.length);
nextIdx += 1;
}
+ });
+ return map;
+ }, [segments, rowMeta]);
+
+ // First profile with an id per display name — mirrors the .find() each row did.
+ const profilesByName = useMemo(() => {
+ const map = new Map<string, SpeakerProfileLite>();
+ for (const profile of speakerProfiles ?? []) {
+ if (profile.id != null && !map.has(profile.display_name)) {
+ map.set(profile.display_name, profile);
+ }
}
return map;
- }, [segments, speakerMappings]);
+ }, [speakerProfiles]);
const consentNotice = (
<div className="shrink-0 flex items-center justify-center gap-1 px-4 pt-2 pb-1 text-[10px] text-muted-foreground/50 select-none">
@@ -774,134 +952,75 @@ export function MeetingTranscriptChat({
)}
<div
ref={scrollRef}
- className="flex-1 min-h-0 overflow-y-auto px-4 pt-2 flex flex-col gap-1.5 agent-chat-scroll pb-[var(--floating-inset,96px)]"
+ className="flex-1 min-h-0 overflow-y-auto px-4 pt-2 agent-chat-scroll pb-[var(--floating-inset,96px)]"
>
- {segments.map((segment, i) => {
- const selfSide = isSelfSide(segment);
- const prevSegment = i > 0 ? segments[i - 1] : null;
- const sameSpeaker = prevSegment
- ? getEffectiveSpeakerKey(prevSegment, speakerMappings) ===
- getEffectiveSpeakerKey(segment, speakerMappings)
- : false;
-
- const hasSpeaker = !!segment.speaker;
- const isOriginallyYou = segment.speaker === "you";
- const isSystemSpeaker = hasSpeaker && !selfSide;
- const effectiveKey = getEffectiveSpeakerKey(segment, speakerMappings);
- const colorIdx = isSystemSpeaker ? (colorByKey.get(effectiveKey) ?? 0) : 0;
- const isSelected = selectedSegmentIds?.has(segment.id) ?? false;
- const selectable = !!onToggleSelect;
-
- const activeName = resolveSegmentSpeakerName(segment, speakerMappings);
- const matchedProfile =
- activeName && speakerProfiles
- ? speakerProfiles.find((p) => p.id != null && p.display_name === activeName)
- : undefined;
- const canAddContact =
- !!matchedProfile &&
- matchedProfile.id != null &&
- !matchedProfile.email &&
- !!onAttachSpeakerEmail;
-
- const labelElement = hasSpeaker && (
- <div className="flex items-center gap-1">
- <SpeakerLabel
- speakerId={segment.speaker!}
- segment={segment}
- resolvedName={activeName}
- speakerProfiles={speakerProfiles}
- participants={participants}
- colorIdx={colorIdx}
- isOriginallyYou={isOriginallyYou}
- onMap={onMapSpeaker}
- onConfirm={onConfirmSuggestion}
- onDismiss={onDismissSuggestion}
- t={t}
- />
- {canAddContact && matchedProfile && matchedProfile.id != null && (
- <AddContactButton
- profile={{ id: matchedProfile.id, display_name: matchedProfile.display_name }}
- onAttachEmail={onAttachSpeakerEmail!}
+ <div style={{ height: totalSize, width: "100%", position: "relative" }}>
+ {virtualizer.getVirtualItems().map((virtualItem) => {
+ const i = virtualItem.index;
+ const segment = segments[i];
+ const selfSide = isSelfSide(segment);
+ const isSystemSpeaker = !!segment.speaker && !selfSide;
+ const { key, activeName } = rowMeta[i];
+ return (
+ <div
+ key={segment.id}
+ data-index={i}
+ ref={virtualizer.measureElement}
+ className="pb-1.5"
+ style={{
+ position: "absolute",
+ top: 0,
+ left: 0,
+ width: "100%",
+ transform: `translateY(${virtualItem.start}px)`,
+ }}
+ >
+ <SegmentRow
+ segment={segment}
+ selfSide={selfSide}
+ sameSpeaker={i > 0 && rowMeta[i - 1].key === key}
+ isFirst={i === 0}
+ isNewest={i === segments.length - 1}
+ colorIdx={isSystemSpeaker ? (colorByKey.get(key) ?? 0) : 0}
+ isSelected={selectedSegmentIds?.has(segment.id) ?? false}
+ activeName={activeName}
+ matchedProfile={activeName ? profilesByName.get(activeName) : undefined}
+ speakerProfiles={speakerProfiles}
+ participants={participants}
+ onMapSpeaker={onMapSpeaker}
+ onConfirmSuggestion={onConfirmSuggestion}
+ onDismissSuggestion={onDismissSuggestion}
+ onAttachSpeakerEmail={onAttachSpeakerEmail}
+ onToggleSelect={onToggleSelect}
t={t}
/>
- )}
- </div>
- );
-
- return (
- <div
- key={segment.id}
- className={cn(
- "group flex flex-col",
- selfSide ? "items-start" : "items-end",
- !sameSpeaker && i > 0 && "mt-2",
- selectable && (selfSide ? "pl-6" : "pr-6")
- )}
- style={{ animation: "agent-message-in 200ms ease-out both" }}
- >
- {labelElement && !sameSpeaker && labelElement}
- {labelElement && sameSpeaker && (
- <div
- className={cn(
- "grid grid-rows-[0fr] opacity-0 pointer-events-none transition-[grid-template-rows,opacity] duration-150 ease-out",
- "group-hover:grid-rows-[1fr] group-hover:opacity-100 group-hover:pointer-events-auto"
- )}
- >
- <div className="overflow-hidden">{labelElement}</div>
- </div>
- )}
- <div className="relative max-w-[80%]">
- <div
- className={cn(
- "px-3 py-1.5 cursor-default transition-colors",
- "text-[13px] leading-relaxed",
- selfSide
- ? cn(
- "bg-primary/90 text-primary-foreground",
- sameSpeaker ? "rounded-lg rounded-tl-sm" : "rounded-lg rounded-bl-sm"
- )
- : cn(
- "bg-surface-2 border border-border/30 text-foreground",
- sameSpeaker ? "rounded-lg rounded-tr-sm" : "rounded-lg rounded-br-sm",
- isSystemSpeaker && cn("border-l-2", SPEAKER_BORDER_COLORS[colorIdx])
- ),
- isSelected && "ring-2 ring-primary/60"
- )}
- >
- {segment.text}
- </div>
- {selectable && (
- <SelectCheckbox
- isSelected={isSelected}
- onToggle={() => onToggleSelect?.(segment.id)}
- className={cn("absolute top-1.5", selfSide ? "-left-6" : "-right-6")}
- />
- )}
</div>
- </div>
- );
- })}
-
- {[
- { text: micPartial, source: "mic" as const, speakerLabel: undefined },
- {
- text: systemPartial,
- source: "system" as const,
- speakerLabel: systemPartialSpeakerLabel,
- },
- ].map(
- ({ text, source, speakerLabel }) =>
- text && (
- <PartialBubble
- key={source}
- text={text}
- source={source}
- speakerLabel={speakerLabel}
- speakerState={source === "system" ? systemPartialSpeakerState : undefined}
- t={t}
- />
- )
- )}
+ );
+ })}
+ </div>
+
+ <div className="flex flex-col gap-1.5">
+ {[
+ { text: micPartial, source: "mic" as const, speakerLabel: undefined },
+ {
+ text: systemPartial,
+ source: "system" as const,
+ speakerLabel: systemPartialSpeakerLabel,
+ },
+ ].map(
+ ({ text, source, speakerLabel }) =>
+ text && (
+ <PartialBubble
+ key={source}
+ text={text}
+ source={source}
+ speakerLabel={speakerLabel}
+ speakerState={source === "system" ? systemPartialSpeakerState : undefined}
+ t={t}
+ />
+ )
+ )}
+ </div>
</div>
</div>
);
diff --git a/src/components/notes/NoteBottomBar.tsx b/src/components/notes/NoteBottomBar.tsx
index 896718f0b..ea90c1019 100644
--- a/src/components/notes/NoteBottomBar.tsx
+++ b/src/components/notes/NoteBottomBar.tsx
@@ -13,6 +13,11 @@ import { getMicAnalyser, useMeetingRecordingStore } from "../../stores/meetingRe
// Module-level buffer: there is a single meeting mic analyser at a time.
const micLevelBuf: { current: Float32Array<ArrayBuffer> | null } = { current: null };
+// While recording, the bar sits over the live streaming transcript, and every
+// partial would force backdrop-blur to re-blur the strip; the capsules trade
+// glass for a near-opaque surface until the recording ends.
+const RECORDING_SURFACE = "bg-surface-2/95 shadow-(--shadow-glass)";
+
function readMeetingMicLevel(): number {
const analyser = getMicAnalyser();
if (!analyser) return useMeetingRecordingStore.getState().currentMicLevel;
@@ -138,7 +143,7 @@ export default function NoteBottomBar({
title={t("notes.editor.stop")}
className={cn(
"group flex items-center gap-2.5 w-full h-11 pl-0.5 pr-3.5 rounded-full",
- GLASS_SURFACE,
+ RECORDING_SURFACE,
"border border-primary/15 dark:border-primary/25",
"transition-[border-color] duration-200",
"hover:border-primary/30 dark:hover:border-primary/40"
@@ -193,9 +198,12 @@ export default function NoteBottomBar({
aria-hidden={hideInput}
className={cn(
"flex-1 min-w-0 flex items-center h-11 gap-2 rounded-full",
- GLASS_SURFACE,
+ isRecording ? RECORDING_SURFACE : GLASS_SURFACE,
"border",
- "transition-all duration-500 [transition-timing-function:cubic-bezier(0.22,1,0.36,1)]",
+ // Named properties, not transition-all: the surface swap below must
+ // land instantly, or every recording start/stop tweens
+ // backdrop-filter for 500ms — the exact cost being removed.
+ "transition-[max-width,opacity,padding,border-color,box-shadow] duration-500 [transition-timing-function:cubic-bezier(0.22,1,0.36,1)]",
hideInput
? "max-w-0 opacity-0 pl-0 pr-0 border-transparent shadow-none pointer-events-none"
: "max-w-[600px] opacity-100 pl-4 pr-1.5",
diff --git a/src/components/ui/LiveWaveform.tsx b/src/components/ui/LiveWaveform.tsx
index 988f3bde4..e518175ec 100644
--- a/src/components/ui/LiveWaveform.tsx
+++ b/src/components/ui/LiveWaveform.tsx
@@ -1,33 +1,25 @@
import { useState, useRef, useEffect } from "react";
import { cn } from "../lib/utils";
+import {
+ WAVE_MAX_PX,
+ WAVE_QUIET_COLOR,
+ WAVE_REST_VISUAL,
+ waveBarColor,
+ waveBarVisual,
+} from "./liveWaveformMath";
const DEFAULT_BAR_COUNT = 40;
const WAVE_SAMPLE_MS = 150;
-const WAVE_MAX_PX = 20;
-const WAVE_MIN_PX = 2;
// Bar width 2px + gap 2px — used to derive the count in "auto" mode.
const WAVE_BAR_PITCH = 4;
const WAVE_MIN_AUTO_BARS = 16;
// Bars scale against a decaying session peak, so any mic gain fills the range.
const WAVE_PEAK_FLOOR = 0.01;
const WAVE_PEAK_DECAY = 0.99;
-const WAVE_QUIET_NORM = 0.14;
-function waveBarStyle(norm: number, index: number, count: number): React.CSSProperties {
- if (norm < WAVE_QUIET_NORM) {
- return { height: WAVE_MIN_PX, backgroundColor: "rgba(143,170,255,0.35)" };
- }
- // Periwinkle (#8FAAFF) → orange (#FFA23E) across the strip, louder = more opaque
- const t = index / (count - 1);
- const r = Math.round(143 + 112 * t);
- const g = Math.round(170 - 8 * t);
- const b = Math.round(255 - 193 * t);
- const alpha = 0.55 + 0.45 * Math.min(1, norm);
- return {
- height: Math.max(WAVE_MIN_PX, Math.round(Math.sqrt(norm) * WAVE_MAX_PX)),
- backgroundColor: `rgba(${r},${g},${b},${alpha})`,
- };
-}
+// The cross-faded quiet/active pair behind every bar (see liveWaveformMath.ts).
+const WAVE_LAYER_CLASS =
+ "absolute inset-0 rounded-full transition-opacity duration-150 ease-out motion-reduce:transition-none";
interface LiveWaveformProps {
/** Returns the current level (RMS, 0..1-ish); sampled every 150ms. */
@@ -42,12 +34,18 @@ export function LiveWaveform({
bars = DEFAULT_BAR_COUNT,
className,
}: LiveWaveformProps) {
- const [samples, setSamples] = useState<number[]>([]);
const peakRef = useRef(WAVE_PEAK_FLOOR);
const containerRef = useRef<HTMLDivElement>(null);
+ const barRefs = useRef<(HTMLDivElement | null)[]>([]);
+ const quietRefs = useRef<(HTMLDivElement | null)[]>([]);
+ const activeRefs = useRef<(HTMLDivElement | null)[]>([]);
+ const levelsRef = useRef<number[]>([]);
const [autoCount, setAutoCount] = useState(DEFAULT_BAR_COUNT);
const count = bars === "auto" ? autoCount : bars;
+ // Read through a ref inside the sampler: in "auto" mode a resize drag can
+ // change the count faster than WAVE_SAMPLE_MS, and a count dependency would
+ // restart the interval each time so it never ticks.
const countRef = useRef(count);
countRef.current = count;
@@ -62,28 +60,66 @@ export function LiveWaveform({
return () => observer.disconnect();
}, [bars]);
+ // Samples are written straight to the bar elements (no setState per tick):
+ // recording never pays React render, layout, or paint cost for the wave.
useEffect(() => {
const id = setInterval(() => {
const level = readLevel();
peakRef.current = Math.max(level, peakRef.current * WAVE_PEAK_DECAY, WAVE_PEAK_FLOOR);
const norm = Math.min(1, level / peakRef.current);
- setSamples((prev) => [...prev.slice(-(countRef.current - 1)), norm]);
+ const barCount = countRef.current;
+ const levels = levelsRef.current;
+ levels.push(norm);
+ if (levels.length > barCount) levels.splice(0, levels.length - barCount);
+ for (let i = 0; i < barCount; i++) {
+ const bar = barRefs.current[i];
+ const quiet = quietRefs.current[i];
+ const active = activeRefs.current[i];
+ if (!bar || !quiet || !active) continue;
+ // History is right-aligned: bars without a sample yet rest at minimum.
+ const { scaleY, quietOpacity, activeOpacity } = waveBarVisual(
+ levels[levels.length - barCount + i] ?? 0
+ );
+ bar.style.transform = `scaleY(${scaleY})`;
+ quiet.style.opacity = String(quietOpacity);
+ active.style.opacity = String(activeOpacity);
+ }
}, WAVE_SAMPLE_MS);
return () => clearInterval(id);
}, [readLevel]);
- const recent = samples.slice(-count);
- const padded =
- recent.length < count ? [...Array<number>(count - recent.length).fill(0), ...recent] : recent;
-
return (
<div ref={containerRef} className={cn("flex items-center gap-0.5 h-5", className)}>
- {padded.map((norm, i) => (
+ {Array.from({ length: count }, (_, i) => (
<div
key={i}
- className="w-0.5 rounded-full shrink-0 transition-[height,background-color] duration-150 ease-out"
- style={waveBarStyle(norm, i, count)}
- />
+ ref={(el) => {
+ barRefs.current[i] = el;
+ }}
+ className="relative w-0.5 shrink-0 transition-transform duration-150 ease-out motion-reduce:transition-none"
+ style={{
+ height: WAVE_MAX_PX,
+ transform: `scaleY(${WAVE_REST_VISUAL.scaleY})`,
+ }}
+ >
+ <div
+ ref={(el) => {
+ quietRefs.current[i] = el;
+ }}
+ className={WAVE_LAYER_CLASS}
+ style={{ backgroundColor: WAVE_QUIET_COLOR, opacity: WAVE_REST_VISUAL.quietOpacity }}
+ />
+ <div
+ ref={(el) => {
+ activeRefs.current[i] = el;
+ }}
+ className={WAVE_LAYER_CLASS}
+ style={{
+ backgroundColor: waveBarColor(i, count),
+ opacity: WAVE_REST_VISUAL.activeOpacity,
+ }}
+ />
+ </div>
))}
</div>
);
diff --git a/src/components/ui/liveWaveformMath.ts b/src/components/ui/liveWaveformMath.ts
new file mode 100644
index 000000000..5065b10d7
--- /dev/null
+++ b/src/components/ui/liveWaveformMath.ts
@@ -0,0 +1,46 @@
+// Bars express loudness through scaleY + layer opacity, never height or
+// background-color: a per-sample layout or paint write every 150ms is the CPU
+// regression this replaces (an animated background-color also retriggers the
+// global `*` background-color transition in index.css). Each bar stacks a
+// uniform quiet layer under a gradient-hued active layer, and a sample
+// cross-fades between them to reproduce the old visuals exactly.
+export const WAVE_MAX_PX = 20;
+const WAVE_MIN_PX = 2;
+const WAVE_QUIET_NORM = 0.14;
+const WAVE_QUIET_OPACITY = 0.35;
+
+// The gradient's periwinkle end, shown uniformly by every quiet bar.
+export const WAVE_QUIET_COLOR = "rgb(143,170,255)";
+
+// Periwinkle (#8FAAFF) → orange (#FFA23E) across the strip, fixed per bar.
+export function waveBarColor(index: number, count: number): string {
+ const t = count > 1 ? index / (count - 1) : 0;
+ const r = Math.round(143 + 112 * t);
+ const g = Math.round(170 - 8 * t);
+ const b = Math.round(255 - 193 * t);
+ return `rgb(${r},${g},${b})`;
+}
+
+// Bars are vertically centered, so scaleY's default center origin reproduces
+// the symmetric growth the old animated height had.
+export function waveBarVisual(norm: number): {
+ scaleY: number;
+ quietOpacity: number;
+ activeOpacity: number;
+} {
+ if (norm < WAVE_QUIET_NORM) {
+ return {
+ scaleY: WAVE_MIN_PX / WAVE_MAX_PX,
+ quietOpacity: WAVE_QUIET_OPACITY,
+ activeOpacity: 0,
+ };
+ }
+ const height = Math.max(WAVE_MIN_PX, Math.round(Math.sqrt(norm) * WAVE_MAX_PX));
+ return {
+ scaleY: height / WAVE_MAX_PX,
+ quietOpacity: 0,
+ activeOpacity: 0.55 + 0.45 * Math.min(1, norm),
+ };
+}
+
+export const WAVE_REST_VISUAL = waveBarVisual(0);
diff --git a/src/helpers/audioActivityDetector.js b/src/helpers/audioActivityDetector.js
index ebae629fa..1510b5fcc 100644
--- a/src/helpers/audioActivityDetector.js
+++ b/src/helpers/audioActivityDetector.js
@@ -12,6 +12,9 @@ const SUSTAINED_THRESHOLD_CHECKS = 2;
const SUSTAINED_EVENT_DRIVEN_MS = 2 * 1000;
const COOLDOWN_MS = 5 * 60 * 1000;
const INACTIVE_RESET_MS = 60 * 1000;
+// PipeWire/PulseAudio emit 'change' subscribe events several times a second on
+// cork/volume churn, and every reconcile forks a pactl subprocess.
+const LINUX_RECONCILE_MIN_SPACING_MS = 1000;
const EXEC_OPTS = { timeout: 5000, encoding: "utf8" };
class AudioActivityDetector extends EventEmitter {
@@ -42,6 +45,8 @@ class AudioActivityDetector extends EventEmitter {
this._linuxOwnershipRequest = 0;
this._linuxReconcileQueued = false;
this._linuxReconcileRunning = false;
+ this._linuxReconcileTimer = null;
+ this._linuxLastReconcileAt = 0;
this._pidScopedCapability = false;
this._externalMicReliable = false;
this._externalMicActive = false;
@@ -169,6 +174,8 @@ class AudioActivityDetector extends EventEmitter {
this._lastKnownMicState = false;
this._clearCooldownReevalTimer();
this._linuxOwnershipRequest++;
+ this._linuxReconcileQueued = false;
+ this._clearLinuxReconcileTimer();
this._pidScopedCapability = false;
this._externalMicReliable = false;
this._externalMicActive = false;
@@ -454,28 +461,58 @@ class AudioActivityDetector extends EventEmitter {
}
// Bursts of subscribe events coalesce into at most one running and one queued
- // reconcile instead of spawning a `pactl list` subprocess per line.
+ // reconcile instead of spawning a `pactl list` subprocess per line, and
+ // successive reconciles stay LINUX_RECONCILE_MIN_SPACING_MS apart: the first
+ // event after quiet reconciles immediately, and a trailing reconcile always
+ // follows the last event of a burst so no state change is dropped.
_queueLinuxReconcile() {
if (this._linuxReconcileQueued) return;
this._linuxReconcileQueued = true;
- if (this._linuxReconcileRunning) return;
+ if (this._linuxReconcileRunning || this._linuxReconcileTimer) return;
+ this._scheduleQueuedLinuxReconcile();
+ }
+ _scheduleQueuedLinuxReconcile() {
+ const waitMs = this._linuxLastReconcileAt + LINUX_RECONCILE_MIN_SPACING_MS - Date.now();
+ if (waitMs <= 0) {
+ this._runQueuedLinuxReconcile();
+ return;
+ }
+ this._linuxReconcileTimer = setTimeout(() => {
+ this._linuxReconcileTimer = null;
+ this._runQueuedLinuxReconcile();
+ }, waitMs);
+ }
+
+ _runQueuedLinuxReconcile() {
this._linuxReconcileRunning = true;
void (async () => {
try {
- while (this._linuxReconcileQueued && this._running && this._listenerProcess) {
- this._linuxReconcileQueued = false;
+ this._linuxReconcileQueued = false;
+ if (this._running && this._listenerProcess) {
await this._reconcileLinuxSourceOutputs(this._startGeneration);
}
} finally {
- this._linuxReconcileQueued = false;
this._linuxReconcileRunning = false;
+ if (this._linuxReconcileQueued && this._running && this._listenerProcess) {
+ this._scheduleQueuedLinuxReconcile();
+ } else {
+ this._linuxReconcileQueued = false;
+ }
}
})();
}
+ _clearLinuxReconcileTimer() {
+ if (this._linuxReconcileTimer) {
+ clearTimeout(this._linuxReconcileTimer);
+ this._linuxReconcileTimer = null;
+ }
+ }
+
async _reconcileLinuxSourceOutputs(generation) {
const request = ++this._linuxOwnershipRequest;
+ this._linuxLastReconcileAt = Date.now();
try {
const { stdout } = await execAsync("pactl --format=json list source-outputs", EXEC_OPTS);
diff --git a/src/helpers/environment.js b/src/helpers/environment.js
index 22e5099f8..a01651c10 100644
--- a/src/helpers/environment.js
+++ b/src/helpers/environment.js
@@ -502,6 +502,32 @@ class EnvironmentManager {
require("dotenv").config({ path: envPath });
return { success: true, path: envPath };
}
+
+ // Removes a single key's line from .env, preserving every other line
+ // verbatim. saveAllKeysToEnvFile() would instead regenerate the file from
+ // PERSISTED_KEYS, dropping hand-added lines (e.g. OPENWHISPR_LOG_LEVEL) and
+ // materializing session/shell env values into the file.
+ removeKeyFromEnvFile(key) {
+ const envPath = path.join(app.getPath("userData"), ".env");
+ envWriteQueue = envWriteQueue.catch(() => {}).then(() => this._removeKeyLine(envPath, key));
+ return envWriteQueue;
+ }
+
+ async _removeKeyLine(envPath, key) {
+ let content;
+ try {
+ content = await fsPromises.readFile(envPath, "utf8");
+ } catch {
+ return; // No .env — nothing to remove.
+ }
+ const keyLine = new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=`);
+ const lines = content.split("\n");
+ const kept = lines.filter((line) => !keyLine.test(line));
+ if (kept.length === lines.length) return;
+ const tmpPath = `${envPath}.tmp`;
+ await fsPromises.writeFile(tmpPath, kept.join("\n"), "utf8");
+ await fsPromises.rename(tmpPath, envPath);
+ }
}
// Generate the uniform BYOK key accessors (getOpenAIKey/saveOpenAIKey/…) from
diff --git a/src/helpers/gpuBinaryManager.js b/src/helpers/gpuBinaryManager.js
index a562accc3..f10662c68 100644
--- a/src/helpers/gpuBinaryManager.js
+++ b/src/helpers/gpuBinaryManager.js
@@ -315,5 +315,21 @@ function migrateLegacyBinDir(managers) {
return clearedPacks;
}
+// An enabled flag with no pack on disk is only reachable via data loss (the
+// 1.8.3 migrateLegacyBinDir deleted lib-carrying packs without recording a
+// notice): the flag is only set after a completed download, and intentional
+// deletes clear it. Returns the affected pack names for the re-download
+// notice; callers must gate re-recording (gpuPackMigrationNotice.recordOnce)
+// so a dismissed notice doesn't return every launch.
+function detectOrphanedGpuPacks(packs) {
+ return packs
+ .filter(
+ ({ manager, enabledEnvVar }) =>
+ process.env[enabledEnvVar] === "true" && manager.isSupported() && !manager.isDownloaded()
+ )
+ .map(({ manager }) => manager.config.name);
+}
+
module.exports = GpuBinaryManager;
module.exports.migrateLegacyBinDir = migrateLegacyBinDir;
+module.exports.detectOrphanedGpuPacks = detectOrphanedGpuPacks;
diff --git a/src/helpers/gpuPackMigrationNotice.js b/src/helpers/gpuPackMigrationNotice.js
index 851e11a62..4fe7b548d 100644
--- a/src/helpers/gpuPackMigrationNotice.js
+++ b/src/helpers/gpuPackMigrationNotice.js
@@ -9,10 +9,20 @@ const { app } = require("electron");
// be lost if the user quit first. See #1606.
const SENTINEL_FILENAME = ".gpu-pack-migration-notice";
+// Launch-time orphan detection (detectOrphanedGpuPacks) finds the same
+// missing pack every launch until the user re-downloads it — including after
+// they saw the toast, dismissed it, and chose not to. This marker limits each
+// pack to one detection-driven notice.
+const FLAGGED_FILENAME = ".gpu-pack-orphan-flagged";
+
function getSentinelPath() {
return path.join(app.getPath("userData"), SENTINEL_FILENAME);
}
+function getFlaggedPath() {
+ return path.join(app.getPath("userData"), FLAGGED_FILENAME);
+}
+
function record(packNames) {
if (!packNames || packNames.length === 0) return;
const existing = read();
@@ -33,10 +43,26 @@ function read() {
}
}
+function recordOnce(packNames) {
+ let flagged = [];
+ try {
+ const { packs } = JSON.parse(fs.readFileSync(getFlaggedPath(), "utf8"));
+ if (Array.isArray(packs)) flagged = packs;
+ } catch {}
+ const unseen = (packNames || []).filter((name) => !flagged.includes(name));
+ if (unseen.length === 0) return;
+ record(unseen);
+ try {
+ fs.writeFileSync(getFlaggedPath(), JSON.stringify({ packs: [...flagged, ...unseen] }));
+ } catch {
+ // Best-effort: the user may be notified again next launch.
+ }
+}
+
function clear() {
try {
fs.unlinkSync(getSentinelPath());
} catch {}
}
-module.exports = { record, read, clear };
+module.exports = { record, recordOnce, read, clear };
diff --git a/src/helpers/ipcHandlers.js b/src/helpers/ipcHandlers.js
index 212578ef5..3b98c16a6 100644
--- a/src/helpers/ipcHandlers.js
+++ b/src/helpers/ipcHandlers.js
@@ -6905,6 +6905,11 @@ class IPCHandlers {
result = await this.whisperManager.transcribeLocalWhisper(wav, {
model: meetingLocalModel,
language: meetingLocalLanguage,
+ // Keep whisper.cpp's default decoder thresholds on this continuous
+ // load: the raised #1458 values multiply temperature-fallback
+ // re-decodes, and meeting chunks already have RMS-gate, VAD, and
+ // holdback/dedup hallucination protection.
+ skipDecoderThresholds: true,
...vadOptions,
});
}
diff --git a/src/helpers/liveSpeakerIdentifier.js b/src/helpers/liveSpeakerIdentifier.js
index fffb97bbd..991fb9483 100644
--- a/src/helpers/liveSpeakerIdentifier.js
+++ b/src/helpers/liveSpeakerIdentifier.js
@@ -49,6 +49,13 @@ const MATCH_THRESHOLD = 0.65;
const MATCH_MARGIN = 0.03;
const LIVE_WINDOW_PADDING_SECONDS = 0.75;
const DEFAULT_VAD_STATE_SHAPE = [2, 1, 64];
+// The VAD graph is tiny (~64 ops per 512-sample window at ~31 Hz); ORT's
+// default thread pool spins one worker per core for no throughput gain.
+const VAD_SESSION_OPTIONS = {
+ intraOpNumThreads: 1,
+ interOpNumThreads: 1,
+ executionMode: "sequential",
+};
function appendFloat32(existing, next) {
if (!existing.length) return next;
@@ -60,16 +67,17 @@ function appendFloat32(existing, next) {
return merged;
}
+function totalSampleCount(chunks) {
+ let total = 0;
+ for (const chunk of chunks) total += chunk.length;
+ return total;
+}
+
function concatFloat32Arrays(chunks) {
if (chunks.length === 0) return new Float32Array(0);
if (chunks.length === 1) return chunks[0];
- let totalLength = 0;
- for (const chunk of chunks) {
- totalLength += chunk.length;
- }
-
- const merged = new Float32Array(totalLength);
+ const merged = new Float32Array(totalSampleCount(chunks));
let offset = 0;
for (const chunk of chunks) {
merged.set(chunk, offset);
@@ -80,8 +88,7 @@ function concatFloat32Arrays(chunks) {
}
function trimChunksToMaxSamples(chunks, maxSamples) {
- let total = 0;
- for (const chunk of chunks) total += chunk.length;
+ let total = totalSampleCount(chunks);
while (total > maxSamples && chunks.length > 0) {
total -= chunks[0].length;
chunks.shift();
@@ -403,7 +410,7 @@ class LiveSpeakerIdentifier {
const ort = loadOnnxRuntime();
if (!ort) return;
- this.session = await ort.InferenceSession.create(vadModelPath);
+ this.session = await ort.InferenceSession.create(vadModelPath, VAD_SESSION_OPTIONS);
this.vadStateInputs = (this.session.inputNames || []).filter((name) => /state|h|c/i.test(name));
this.vadStateOutputs = (this.session.outputNames || []).filter((name) =>
/state|h|c/i.test(name)
@@ -571,14 +578,12 @@ class LiveSpeakerIdentifier {
}
async _identifyActiveSpeechSegment(force = false) {
- const allSamples = concatFloat32Arrays(this.speechChunks);
- if (allSamples.length < LIVE_IDENTIFICATION_MIN_SAMPLES) {
+ // Runs on every speech window (~31x/sec), so the cheap gates must come
+ // first — concatenating up to 32s of float32 per window is ~64 MB/s of
+ // wasted main-thread memcpy during continuous speech.
+ if (totalSampleCount(this.speechChunks) < LIVE_IDENTIFICATION_MIN_SAMPLES) {
return;
}
- const currentSamples =
- allSamples.length > MAX_EMBEDDING_SAMPLES
- ? allSamples.subarray(allSamples.length - MAX_EMBEDDING_SAMPLES)
- : allSamples;
if (
!force &&
@@ -589,6 +594,12 @@ class LiveSpeakerIdentifier {
return;
}
+ const allSamples = concatFloat32Arrays(this.speechChunks);
+ const currentSamples =
+ allSamples.length > MAX_EMBEDDING_SAMPLES
+ ? allSamples.subarray(allSamples.length - MAX_EMBEDDING_SAMPLES)
+ : allSamples;
+
const embedding = await speakerEmbeddings.extractEmbeddingFromSamples(currentSamples);
if (!embedding) {
return;
diff --git a/src/helpers/qdrantManager.js b/src/helpers/qdrantManager.js
index dc1a4f70b..b10857707 100644
--- a/src/helpers/qdrantManager.js
+++ b/src/helpers/qdrantManager.js
@@ -1,4 +1,5 @@
const { spawn } = require("child_process");
+const EventEmitter = require("events");
const fs = require("fs");
const path = require("path");
const http = require("http");
@@ -10,6 +11,7 @@ const {
gracefulStopProcess,
} = require("../utils/serverUtils");
const sidecarPidFile = require("./sidecarPidFile");
+const { waitForExit } = require("./sidecarReaper");
const PORT_RANGE_START = 6333;
const PORT_RANGE_END = 6350;
@@ -17,6 +19,15 @@ const STARTUP_TIMEOUT_MS = 30000;
const STARTUP_POLL_INTERVAL_MS = 100;
const HEALTH_CHECK_INTERVAL_MS = 5000;
const HEALTH_CHECK_TIMEOUT_MS = 2000;
+// A wedged qdrant (alive but failing health checks, observed spinning at full
+// CPU) is restarted after ~40s of consecutive failures. Restarts are capped
+// per session so a genuinely broken binary doesn't crash-loop; note search
+// falls back to FTS5 keywords while qdrant is down.
+const HEALTH_FAILURES_BEFORE_RESTART = 8;
+const MAX_RESTARTS_PER_SESSION = 3;
+// gracefulStopProcess can resolve right after sending SIGKILL, so a restart
+// verifies the old process is really gone before spawning its replacement.
+const RESTART_EXIT_WAIT_MS = 2000;
const STORAGE_DIR = path.join(
os.homedir(),
@@ -25,14 +36,21 @@ const STORAGE_DIR = path.join(
process.env.NODE_ENV === "development" ? "qdrant-data-dev" : "qdrant-data"
);
-class QdrantManager {
+// Emits "restarted" (port) after a successful unhealthy-restart so the
+// composition root can re-wire clients (the replacement may be on a new port).
+class QdrantManager extends EventEmitter {
constructor() {
+ super();
this.process = null;
this.port = null;
this.ready = false;
this.startupPromise = null;
this.healthCheckInterval = null;
this.cachedBinaryPath = null;
+ this.consecutiveHealthFailures = 0;
+ this.restartCount = 0;
+ this.restarting = false;
+ this.stopRequested = false;
}
getBinaryPath() {
@@ -52,9 +70,16 @@ class QdrantManager {
}
async start() {
+ // Only this public entry clears a deliberate stop; the restart path must
+ // not resurrect a stopRequested that an app quit set mid-restart.
+ this.stopRequested = false;
+ await this._start();
+ }
+
+ async _start() {
if (this.startupPromise) return this.startupPromise;
if (this.ready) return;
- if (this.process) await this.stop();
+ if (this.process) await this._stopProcess();
this.startupPromise = this._doStart();
try {
@@ -70,6 +95,15 @@ class QdrantManager {
this.port = await findAvailablePort(PORT_RANGE_START, PORT_RANGE_END);
+ // A deliberate stop (app quit) can land during the port scan, when there
+ // is no process for it to kill; abort instead of spawning a child that
+ // outlives the app.
+ if (this.stopRequested) {
+ this.port = null;
+ debugLogger.debug("qdrant start aborted by stop request");
+ return;
+ }
+
fs.mkdirSync(STORAGE_DIR, { recursive: true });
const configPath = path.join(STORAGE_DIR, "config.yaml");
@@ -94,38 +128,42 @@ class QdrantManager {
storagePath,
});
- this.process = spawn(binaryPath, ["--config-path", configPath], {
+ const child = spawn(binaryPath, ["--config-path", configPath], {
cwd: STORAGE_DIR,
stdio: ["ignore", "pipe", "pipe"],
windowsHide: true,
detached: process.platform !== "win32",
});
- sidecarPidFile.write("qdrant", this.process.pid);
+ this.process = child;
+ sidecarPidFile.write("qdrant", child.pid);
let stderrBuffer = "";
let lastErrorLine = "";
let exitCode = null;
- this.process.stdout.on("data", (data) => {
+ child.stdout.on("data", (data) => {
const text = data.toString();
debugLogger.debug("qdrant stdout", { data: text.trim() });
const errorLine = text.split("\n").findLast((line) => line.includes(" ERROR "));
if (errorLine) lastErrorLine = errorLine.trim();
});
- this.process.stderr.on("data", (data) => {
+ child.stderr.on("data", (data) => {
stderrBuffer += data.toString();
debugLogger.debug("qdrant stderr", { data: data.toString().trim() });
});
- this.process.on("error", (error) => {
+ child.on("error", (error) => {
debugLogger.error("qdrant process error", { error: error.message });
- this.ready = false;
+ if (this.process === child) this.ready = false;
});
- this.process.on("close", (code) => {
+ child.on("close", (code) => {
exitCode = code;
debugLogger.debug("qdrant process exited", { code });
+ // A straggler close from a child already replaced by a restart must not
+ // clobber the new process's state or pid entry.
+ if (this.process !== child) return;
this.ready = false;
this.process = null;
this._stopHealthCheck();
@@ -197,14 +235,23 @@ class QdrantManager {
_startHealthCheck() {
this._stopHealthCheck();
+ this.consecutiveHealthFailures = 0;
this.healthCheckInterval = setInterval(async () => {
if (!this.process) {
this._stopHealthCheck();
return;
}
- if (!(await this._checkHealth())) {
- debugLogger.warn("qdrant health check failed");
- this.ready = false;
+ if (await this._checkHealth()) {
+ this.consecutiveHealthFailures = 0;
+ return;
+ }
+ this.consecutiveHealthFailures++;
+ debugLogger.warn("qdrant health check failed", {
+ consecutiveFailures: this.consecutiveHealthFailures,
+ });
+ this.ready = false;
+ if (this.consecutiveHealthFailures >= HEALTH_FAILURES_BEFORE_RESTART) {
+ this._restartUnhealthy();
}
}, HEALTH_CHECK_INTERVAL_MS);
}
@@ -216,10 +263,56 @@ class QdrantManager {
}
}
+ // Never rejects; called fire-and-forget from the health-check interval.
+ async _restartUnhealthy() {
+ if (this.restarting) return;
+ this.restarting = true;
+ try {
+ if (this.restartCount >= MAX_RESTARTS_PER_SESSION) {
+ await this._stopProcess();
+ debugLogger.warn(
+ "qdrant still unhealthy after max restarts, leaving it stopped (note search falls back to FTS5 keywords)",
+ { maxRestarts: MAX_RESTARTS_PER_SESSION }
+ );
+ return;
+ }
+ this.restartCount++;
+ debugLogger.warn("qdrant unresponsive, restarting", {
+ attempt: this.restartCount,
+ maxRestarts: MAX_RESTARTS_PER_SESSION,
+ });
+ const pid = this.process?.pid;
+ await this._stopProcess();
+ if (pid && !(await waitForExit(pid, RESTART_EXIT_WAIT_MS))) {
+ // Mirror the reaper's policy: keep the pid entry so the next launch retries.
+ sidecarPidFile.write("qdrant", pid);
+ debugLogger.error("qdrant survived SIGKILL, not restarting", { pid });
+ return;
+ }
+ if (this.stopRequested) return; // a deliberate stop (app quit) raced the restart
+ await this._start();
+ if (this.ready) this.emit("restarted", this.port);
+ } catch (error) {
+ // _doStart can reject after spawning (e.g. startup timeout); make sure
+ // the replacement really is stopped, not left running unsupervised.
+ await this._stopProcess();
+ debugLogger.warn("qdrant restart failed, leaving it stopped", { error: error.message });
+ } finally {
+ this.restarting = false;
+ }
+ }
+
async stop() {
+ // A deliberate stop also cancels any in-flight unhealthy restart.
+ this.stopRequested = true;
+ await this._stopProcess();
+ }
+
+ async _stopProcess() {
this._stopHealthCheck();
- if (!this.process) {
+ const child = this.process;
+ if (!child) {
this.ready = false;
return;
}
@@ -227,12 +320,18 @@ class QdrantManager {
debugLogger.debug("Stopping qdrant");
try {
- await gracefulStopProcess(this.process);
+ await gracefulStopProcess(child);
} catch (error) {
debugLogger.error("Error stopping qdrant", { error: error.message });
}
- this.process = null;
+ // On the SIGKILL escalation path gracefulStopProcess resolves before
+ // 'close' fires, so clean up here; the close handler's guard skips the
+ // straggler event.
+ if (this.process === child) {
+ this.process = null;
+ sidecarPidFile.clear("qdrant");
+ }
this.ready = false;
this.port = null;
}
@@ -255,3 +354,5 @@ class QdrantManager {
}
module.exports = QdrantManager;
+module.exports.HEALTH_FAILURES_BEFORE_RESTART = HEALTH_FAILURES_BEFORE_RESTART;
+module.exports.MAX_RESTARTS_PER_SESSION = MAX_RESTARTS_PER_SESSION;
diff --git a/src/helpers/sidecarReaper.js b/src/helpers/sidecarReaper.js
index 0d978db84..530c80b52 100644
--- a/src/helpers/sidecarReaper.js
+++ b/src/helpers/sidecarReaper.js
@@ -103,4 +103,4 @@ async function reapStaleSidecars({
);
}
-module.exports = { reapStaleSidecars };
+module.exports = { reapStaleSidecars, waitForExit };
diff --git a/src/helpers/whisper.js b/src/helpers/whisper.js
index 175e2378c..6c48409ed 100644
--- a/src/helpers/whisper.js
+++ b/src/helpers/whisper.js
@@ -394,6 +394,7 @@ class WhisperManager {
vadEnabled,
vadConfig,
signal: options.signal,
+ skipDecoderThresholds: options.skipDecoderThresholds === true,
});
}
@@ -462,6 +463,7 @@ class WhisperManager {
language,
initialPrompt,
signal: options.signal,
+ skipDecoderThresholds: options.skipDecoderThresholds,
});
const elapsed = Date.now() - startTime;
diff --git a/src/helpers/whisperGpuUpgradeReset.js b/src/helpers/whisperGpuUpgradeReset.js
new file mode 100644
index 000000000..d804a9a5a
--- /dev/null
+++ b/src/helpers/whisperGpuUpgradeReset.js
@@ -0,0 +1,47 @@
+const fs = require("fs");
+const path = require("path");
+const { app } = require("electron");
+const debugLogger = require("./debugLogger");
+
+// WHISPER_GPU_FAILED persists until a manual Retry, so a GPU knocked out once
+// (a driver hiccup, or 1.8.3's pack deletion) stays on CPU whisper forever.
+// This sentinel remembers the last app version that ran: on the first launch
+// of a new version the remembered failure is cleared, giving the GPU exactly
+// one fresh attempt per upgrade — a real failure re-records the flag on the
+// next server start. Must run before the whisper server pre-warm resolves its
+// GPU options.
+const SENTINEL_FILENAME = ".whisper-gpu-retry-version";
+
+function getSentinelPath() {
+ return path.join(app.getPath("userData"), SENTINEL_FILENAME);
+}
+
+function resetWhisperGpuFailureOnUpgrade(environmentManager) {
+ const version = app.getVersion();
+ let lastRun = null;
+ try {
+ lastRun = fs.readFileSync(getSentinelPath(), "utf8").trim();
+ } catch {}
+ if (lastRun === version) return false;
+ try {
+ fs.writeFileSync(getSentinelPath(), version);
+ } catch {
+ // Best-effort: without the sentinel the flag is cleared again next launch.
+ }
+ if (!process.env.WHISPER_GPU_FAILED) return false;
+ delete process.env.WHISPER_GPU_FAILED;
+ debugLogger.info("Cleared remembered whisper GPU failure for a fresh attempt after upgrade", {
+ from: lastRun,
+ to: version,
+ });
+ // Targeted removal: a full saveAllKeysToEnvFile() rewrite would drop
+ // hand-added .env lines (e.g. OPENWHISPR_LOG_LEVEL=debug).
+ environmentManager.removeKeyFromEnvFile("WHISPER_GPU_FAILED").catch((err) => {
+ debugLogger.error("Failed to persist WHISPER_GPU_FAILED clear to .env", {
+ error: err.message,
+ });
+ });
+ return true;
+}
+
+module.exports = { resetWhisperGpuFailureOnUpgrade };
diff --git a/src/helpers/whisperServer.js b/src/helpers/whisperServer.js
index 928d94e0d..1817b7022 100644
--- a/src/helpers/whisperServer.js
+++ b/src/helpers/whisperServer.js
@@ -33,11 +33,15 @@ const DEFAULT_WHISPER_THREADS = 4;
const MAX_AUTO_WHISPER_THREADS = 12;
const MAX_MANUAL_WHISPER_THREADS = 64;
const AUTO_THREAD_RATIO = 0.75;
-// Decoder anti-hallucination thresholds sent with every /inference request. whisper.cpp's
+// Decoder anti-hallucination thresholds sent with /inference requests. whisper.cpp's
// defaults (entropy 2.4, logprob -1.0) let a mostly-silent 30s decode window pass the
// repetition check and emit training-data outro boilerplate ("Thank you for watching",
// "Продолжение следует..."). These values cut the hallucinated-tail rate from 2.25% to
-// 0.06% over 4,814 real dictations. See #1458.
+// 0.06% over 4,814 real dictations. See #1458. The raised entropy also sends more
+// windows into whisper.cpp's temperature-fallback loop (re-decoding a window up to
+// ~6x), which a continuous load cannot afford: meeting chunks pass
+// skipDecoderThresholds to keep the server defaults — they already have RMS-gate,
+// VAD, and holdback/dedup hallucination protection.
const INFERENCE_DECODER_FIELDS = Object.freeze({
entropy_thold: "2.8",
logprob_thold: "-1.25",
@@ -138,6 +142,24 @@ function getVadSignature(options = {}) {
return `vad:on:${options.vadModelPath}:${JSON.stringify(vadConfig)}`;
}
+// An explicit option wins (set by the one-shot pin restart; -1 means
+// "explicitly unpinned", so a stale env value must not resurface), else the
+// persisted choice from a prior run.
+function resolveVulkanDeviceIndex(options = {}) {
+ if (Number.isInteger(options.vulkanDeviceIndex)) return options.vulkanDeviceIndex;
+ const persisted = parseInt(process.env.WHISPER_VULKAN_DEVICE, 10);
+ return Number.isInteger(persisted) && persisted >= 0 ? persisted : null;
+}
+
+function getGpuSignature(options = {}) {
+ const useCuda = options.useCuda === true;
+ const useVulkan = !useCuda && options.useVulkan === true;
+ if (useCuda) return "gpu:cuda";
+ if (!useVulkan) return "gpu:cpu";
+ const deviceIndex = resolveVulkanDeviceIndex(options);
+ return `gpu:vulkan:${Number.isInteger(deviceIndex) && deviceIndex >= 0 ? deviceIndex : "default"}`;
+}
+
function buildWhisperServerArgs({
modelPath,
port,
@@ -286,6 +308,8 @@ class WhisperServerManager extends EventEmitter {
this._stopRequested = false;
this.vadSignature = "vad:off";
this.threadSignature = "threads:default";
+ this.gpuSignature = "gpu:cpu";
+ this.gpuFallbackActive = false;
this.lastStartOptions = {};
}
@@ -492,12 +516,20 @@ class WhisperServerManager extends EventEmitter {
const threadResolution = resolveWhisperThreads(options);
const nextThreadSignature = getThreadSignature(threadResolution);
const nextVadSignature = getVadSignature(options);
+ const nextGpuSignature = getGpuSignature(options);
+ // gpuFallbackActive pins a fallback session to its working CPU server:
+ // after a CUDA crash the next request can resolve to a different backend
+ // (an installed Vulkan pack, since only the crashed backend is recorded in
+ // WHISPER_GPU_FAILED) and must not tear the session down for a GPU cold
+ // start mid-dictation. stop() clears the pin, so pack downloads, explicit
+ // retries, and app restarts get a fresh GPU attempt.
if (
this.ready &&
this.modelPath === modelPath &&
!this.isRemote &&
this.vadSignature === nextVadSignature &&
- this.threadSignature === nextThreadSignature
+ this.threadSignature === nextThreadSignature &&
+ (this.gpuSignature === nextGpuSignature || this.gpuFallbackActive)
) {
return;
}
@@ -535,18 +567,19 @@ class WhisperServerManager extends EventEmitter {
this.useCuda = usingCuda;
this.useVulkan = usingVulkan;
- // Pin Vulkan to a specific device: an explicit option wins (set by the
- // one-shot restart below; -1 means "explicitly unpinned", so the stale env
- // value must not resurface), else the persisted choice from a prior run.
- let vulkanDeviceIndex = null;
- if (usingVulkan) {
- if (Number.isInteger(options.vulkanDeviceIndex)) {
- vulkanDeviceIndex = options.vulkanDeviceIndex;
- } else {
- const persisted = parseInt(process.env.WHISPER_VULKAN_DEVICE, 10);
- if (Number.isInteger(persisted) && persisted >= 0) vulkanDeviceIndex = persisted;
- }
- }
+ // Pin Vulkan to a specific device (see resolveVulkanDeviceIndex; the
+ // one-shot restart below passes the explicit index).
+ const vulkanDeviceIndex = usingVulkan ? resolveVulkanDeviceIndex(options) : null;
+
+ // Track what this server actually runs, not what start() was asked for:
+ // the GPU-failure fallback and the one-shot Vulkan pin restart re-enter
+ // _doStart with corrected flags, and the guard in start() must no-op on
+ // the next request with the same resolved flags instead of restart-looping.
+ this.gpuSignature = getGpuSignature({
+ useCuda: usingCuda,
+ useVulkan: usingVulkan,
+ vulkanDeviceIndex: vulkanDeviceIndex ?? -1,
+ });
// Check for FFmpeg first - only use --convert flag if FFmpeg is available
const ffmpegPath = this.getFFmpegPath();
@@ -662,6 +695,7 @@ class WhisperServerManager extends EventEmitter {
);
this.emit(usingCuda ? "cuda-fallback" : "gpu-fallback");
await this.stop();
+ this.gpuFallbackActive = true;
return this._doStart(modelPath, { ...options, useCuda: false, useVulkan: false });
}
if (shouldFallbackToDefaultThreads(threadResolution)) {
@@ -837,7 +871,7 @@ class WhisperServerManager extends EventEmitter {
});
// signal is optional; only cancellable uploads pass one.
- const { language, initialPrompt, signal } = options;
+ const { language, initialPrompt, signal, skipDecoderThresholds } = options;
if (signal?.aborted) throw createAbortError("whisper-server transcription cancelled");
// Always convert to 16kHz mono WAV - whisper.cpp requires this exact format
@@ -866,12 +900,14 @@ class WhisperServerManager extends EventEmitter {
`${language || "auto"}\r\n`
);
- for (const [name, value] of Object.entries(INFERENCE_DECODER_FIELDS)) {
- parts.push(
- `--${boundary}\r\n` +
- `Content-Disposition: form-data; name="${name}"\r\n\r\n` +
- `${value}\r\n`
- );
+ if (!skipDecoderThresholds) {
+ for (const [name, value] of Object.entries(INFERENCE_DECODER_FIELDS)) {
+ parts.push(
+ `--${boundary}\r\n` +
+ `Content-Disposition: form-data; name="${name}"\r\n\r\n` +
+ `${value}\r\n`
+ );
+ }
}
// Add initial prompt for custom dictionary words
@@ -1052,6 +1088,7 @@ class WhisperServerManager extends EventEmitter {
model: modelPath ? path.basename(modelPath) : null,
});
await this.start(modelPath, { ...this.lastStartOptions, useCuda: false, useVulkan: false });
+ this.gpuFallbackActive = true;
// Emit only once the CPU server is up — the notification tells the user CPU is in use
this.emit(backend === "cuda" ? "cuda-fallback" : "gpu-fallback");
return await this._postInference(body, boundary);
@@ -1089,6 +1126,7 @@ class WhisperServerManager extends EventEmitter {
async stop() {
this._stopRequested = true;
+ this.gpuFallbackActive = false;
this.stopHealthCheck();
if (this.isRemote) {
@@ -1163,6 +1201,7 @@ module.exports.INFERENCE_DECODER_FIELDS = INFERENCE_DECODER_FIELDS;
module.exports.parseVulkanDevices = parseVulkanDevices;
module.exports.resolveVulkanPinAction = resolveVulkanPinAction;
module.exports.getVadSignature = getVadSignature;
+module.exports.getGpuSignature = getGpuSignature;
module.exports.resolveWhisperThreads = resolveWhisperThreads;
module.exports.shouldFallbackToCpuAfterRequestError = shouldFallbackToCpuAfterRequestError;
module.exports.shouldRetryAfterServerReplaced = shouldRetryAfterServerReplaced;
diff --git a/test/components/liveWaveform.test.js b/test/components/liveWaveform.test.js
new file mode 100644
index 000000000..1735adc1d
--- /dev/null
+++ b/test/components/liveWaveform.test.js
@@ -0,0 +1,58 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { renderStatic } = require("../helpers/harness/reactSsr");
+
+const loadMath = () => import("../../src/components/ui/liveWaveformMath.ts");
+const loadComponent = () => import("../../src/components/ui/LiveWaveform.tsx");
+
+test("bar color is fixed per index: a gradient from periwinkle to orange", async () => {
+ const { waveBarColor, WAVE_QUIET_COLOR } = await loadMath();
+
+ assert.equal(waveBarColor(0, 40), "rgb(143,170,255)");
+ assert.equal(waveBarColor(39, 40), "rgb(255,162,62)");
+ // A single bar must not divide by zero.
+ assert.equal(waveBarColor(0, 1), "rgb(143,170,255)");
+ // The quiet layer is the gradient's periwinkle end, uniform across the strip.
+ assert.equal(WAVE_QUIET_COLOR, "rgb(143,170,255)");
+});
+
+test("per-sample visuals keep the old height/alpha curve as scaleY + layer opacity", async () => {
+ const { waveBarVisual } = await loadMath();
+
+ // Quiet floor: the old uniform 2px periwinkle bar at 0.35 alpha — the
+ // gradient-hued active layer is fully faded out.
+ assert.deepEqual(waveBarVisual(0), { scaleY: 2 / 20, quietOpacity: 0.35, activeOpacity: 0 });
+ assert.deepEqual(waveBarVisual(0.13), { scaleY: 2 / 20, quietOpacity: 0.35, activeOpacity: 0 });
+
+ // Loud: height = round(sqrt(norm) * 20), alpha = 0.55 + 0.45 * norm on the
+ // gradient layer, quiet layer fully faded out.
+ assert.deepEqual(waveBarVisual(0.5), {
+ scaleY: Math.round(Math.sqrt(0.5) * 20) / 20,
+ quietOpacity: 0,
+ activeOpacity: 0.55 + 0.45 * 0.5,
+ });
+ assert.deepEqual(waveBarVisual(1), { scaleY: 1, quietOpacity: 0, activeOpacity: 1 });
+});
+
+test("bars render with static colors and compositor-only animated properties", async () => {
+ const { LiveWaveform } = await loadComponent();
+
+ const html = renderStatic(LiveWaveform, { readLevel: () => 0, bars: 5 });
+
+ // Five bars at the rest scale, each with a fixed layout height.
+ assert.equal(html.split("scaleY(0.1)").length - 1, 5);
+ assert.equal(html.split("height:20px").length - 1, 5);
+
+ // At rest every bar shows only the uniform quiet periwinkle at 0.35 alpha…
+ assert.equal(html.split("background-color:rgb(143,170,255);opacity:0.35").length - 1, 5);
+ // …while each bar's gradient-hued active layer is fully faded out.
+ assert.equal(html.split('opacity:0"').length - 1, 5);
+ assert.ok(html.includes('background-color:rgb(255,162,62);opacity:0"'));
+
+ // The regression being fixed: bars must not transition height or
+ // background-color (both retrigger layout/paint on every 150ms sample).
+ assert.ok(html.includes("transition-transform"));
+ assert.ok(html.includes("transition-opacity"));
+ assert.ok(!html.includes("transition-[height"));
+ assert.ok(!html.includes("background-color]"));
+});
diff --git a/test/components/meetingTranscriptChat.test.js b/test/components/meetingTranscriptChat.test.js
new file mode 100644
index 000000000..0d9f10e8a
--- /dev/null
+++ b/test/components/meetingTranscriptChat.test.js
@@ -0,0 +1,90 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("node:fs");
+const path = require("node:path");
+const i18next = require("i18next");
+const { initReactI18next } = require("react-i18next");
+const { renderStatic } = require("../helpers/harness/reactSsr");
+
+const SEGMENTS = [
+ { id: "s1", text: "hello from mic", source: "mic", timestamp: 1 },
+ { id: "s2", text: "hi from remote", source: "system", timestamp: 2, speaker: "speaker_0" },
+ { id: "s3", text: "second remote line", source: "system", timestamp: 3, speaker: "speaker_0" },
+];
+
+async function renderChat(props) {
+ if (!i18next.isInitialized) {
+ const en = JSON.parse(
+ fs.readFileSync(path.join(__dirname, "../../src/locales/en/translation.json"), "utf8")
+ );
+ await i18next.use(initReactI18next).init({
+ lng: "en",
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+ });
+ }
+ const mod = await import("../../src/components/notes/MeetingTranscriptChat.tsx");
+ return renderStatic(mod.MeetingTranscriptChat, { segments: SEGMENTS, ...props });
+}
+
+test("rows resolve speaker labels through the live mappings", async () => {
+ const unmapped = await renderChat({ speakerMappings: {} });
+ assert.ok(unmapped.includes("Speaker 1"), "unmapped cluster shows its numbered label");
+
+ const renamed = await renderChat({ speakerMappings: { speaker_0: "Alice" } });
+ assert.ok(renamed.includes("Alice"), "renaming the cluster renames the rows");
+ assert.ok(!renamed.includes("Speaker 1"));
+});
+
+test("consecutive rows of one speaker collapse the repeat label behind hover", async () => {
+ const html = await renderChat({});
+ // s3 follows s2 with the same effective speaker key.
+ assert.equal(html.split("grid-rows-[0fr]").length - 1, 1);
+});
+
+test("selection ring follows selectedSegmentIds", async () => {
+ const html = await renderChat({
+ selectedSegmentIds: new Set(["s2"]),
+ onToggleSelect: () => {},
+ });
+ assert.equal(html.split("ring-2 ring-primary/60").length - 1, 1);
+});
+
+test("a mapped profile without an email offers the add-contact affordance", async () => {
+ const html = await renderChat({
+ speakerMappings: { speaker_0: "Alice" },
+ speakerProfiles: [{ id: 7, display_name: "Alice", email: null }],
+ onAttachSpeakerEmail: () => {},
+ });
+ assert.ok(html.includes("Add contact"));
+
+ const withEmail = await renderChat({
+ speakerMappings: { speaker_0: "Alice" },
+ speakerProfiles: [{ id: 7, display_name: "Alice", email: "[email protected]" }],
+ onAttachSpeakerEmail: () => {},
+ });
+ assert.ok(!withEmail.includes("Add contact"));
+});
+
+test("a long transcript renders only a window of rows, each animating at most once", async () => {
+ const many = Array.from({ length: 500 }, (_, i) => ({
+ id: `m${i}`,
+ text: `line ${i}`,
+ source: "system",
+ timestamp: i,
+ speaker: `speaker_${i % 3}`,
+ }));
+ const html = await renderChat({ segments: many });
+
+ const rendered = html.split("data-index=").length - 1;
+ assert.ok(rendered > 0, "the first screenful renders before the scroller is measured");
+ assert.ok(rendered < 60, `expected a window, got ${rendered} of 500 rows`);
+ // A remounting row must not replay its entrance while the list scrolls.
+ assert.ok(html.split("agent-message-in").length - 1 <= 1);
+});
+
+test("live partials render alongside the settled rows", async () => {
+ const html = await renderChat({ micPartial: "still talking" });
+ assert.ok(html.includes("still talking"));
+ assert.ok(html.includes("hello from mic"));
+});
diff --git a/test/components/noteBottomBar.test.js b/test/components/noteBottomBar.test.js
new file mode 100644
index 000000000..c40defe87
--- /dev/null
+++ b/test/components/noteBottomBar.test.js
@@ -0,0 +1,59 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const { createElement } = require("react");
+const { renderToStaticMarkup } = require("react-dom/server");
+const { createRendererServer, installBrowserGlobals } = require("../lib/rendererTestHarness");
+
+// Assertions are class-based, so the untranslated i18n fallback (raw keys) is fine.
+async function renderBottomBar(t, props) {
+ installBrowserGlobals(t);
+ const vite = await createRendererServer(t, {
+ cachePrefix: "openwhispr-note-bottom-bar-test-",
+ mockModules: {
+ "/stores/meetingRecordingStore": `
+ export const getMicAnalyser = () => null;
+ export const useMeetingRecordingStore = { getState: () => ({ currentMicLevel: 0 }) };
+ `,
+ },
+ });
+ const mod = await vite.ssrLoadModule("/components/notes/NoteBottomBar.tsx");
+ return renderToStaticMarkup(
+ createElement(mod.default, {
+ isRecording: false,
+ isProcessing: false,
+ onStartRecording: () => {},
+ onStopRecording: () => {},
+ onAskSubmit: () => {},
+ ...props,
+ })
+ );
+}
+
+test("recording state renders no backdrop-filter surface over the live transcript", async (t) => {
+ const html = await renderBottomBar(t, { isRecording: true });
+
+ // The 1.9.0 CPU regression: every transcript partial re-blurred the strip.
+ assert.ok(!html.includes("backdrop-blur"), "no backdrop-blur while recording");
+ assert.ok(!html.includes("backdrop-saturate"), "no backdrop-saturate while recording");
+ assert.ok(html.includes("bg-surface-2/95"), "capsules use the near-opaque surface");
+ assert.ok(html.includes("shadow-(--shadow-glass)"), "capsules keep the glass rim shadow");
+});
+
+test("idle state keeps the liquid-glass capsule", async (t) => {
+ const html = await renderBottomBar(t, { isRecording: false });
+
+ assert.ok(html.includes("backdrop-blur-xl"));
+ assert.ok(html.includes("backdrop-saturate-150"));
+});
+
+test("the ask capsule never transitions its surface between the two states", async (t) => {
+ // transition-all would tween backdrop-filter and background-color for 500ms
+ // on every recording start and stop, re-paying the cost this change removes.
+ for (const isRecording of [false, true]) {
+ const html = await renderBottomBar(t, { isRecording });
+ assert.ok(
+ html.includes("transition-[max-width,opacity,padding,border-color,box-shadow]"),
+ `capsule transition is property-scoped (isRecording=${isRecording})`
+ );
+ }
+});
diff --git a/test/helpers/audioActivityDetector.test.js b/test/helpers/audioActivityDetector.test.js
index 5cfd60061..b0c5c6383 100644
--- a/test/helpers/audioActivityDetector.test.js
+++ b/test/helpers/audioActivityDetector.test.js
@@ -107,6 +107,9 @@ function createDetector(
}
const flush = () => new Promise((resolve) => setTimeout(resolve, 0));
+// flush() pends on the mocked setTimeout, so mock-timer tests drain the
+// reconcile promise chain through the unmocked immediate queue instead.
+const flushImmediate = () => new Promise((resolve) => setImmediate(resolve));
const createDeferred = () => {
let resolve;
let reject;
@@ -494,7 +497,11 @@ test("win32: unattributable sessions (pid 0) count as external capture", async (
detector.stop();
});
-test("linux: reconciles source-output ownership at startup and on events", async () => {
+// Mirrors LINUX_RECONCILE_MIN_SPACING_MS in audioActivityDetector.js.
+const RECONCILE_SPACING_MS = 1000;
+
+test("linux: reconciles source-output ownership at startup and on events", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });
const { detector, children, execCalls } = createDetector("linux", {
excludedProcessIds: () => [700],
execResponses: [
@@ -519,8 +526,9 @@ test("linux: reconciles source-output ownership at startup and on events", async
externalMicActive: true,
});
+ t.mock.timers.tick(RECONCILE_SPACING_MS);
children[0].stdout.emit("data", "Event 'change' on source-output #1\n");
- await flush();
+ await flushImmediate();
assert.deepEqual(
execCalls.map(({ command }) => command),
@@ -533,42 +541,91 @@ test("linux: reconciles source-output ownership at startup and on events", async
detector.stop();
});
-test("linux: a burst of subscribe events coalesces into at most two reconciles", async () => {
+test("linux: a subscribe-event burst runs one leading and one spaced trailing reconcile", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });
const { detector, children, execCalls } = createDetector("linux", {
excludedProcessIds: () => [700],
execResponses: [
{ stdout: "[]" },
- { stdout: JSON.stringify([{ index: 1, properties: { "application.process.id": "800" } }]) },
+ { stdout: "[]" },
{ stdout: JSON.stringify([{ index: 1, properties: { "application.process.id": "800" } }]) },
],
});
+ const reconciles = () =>
+ execCalls.filter(({ command }) => command === "pactl --format=json list source-outputs").length;
await detector.start();
+ t.mock.timers.tick(RECONCILE_SPACING_MS);
+
children[0].stdout.emit(
"data",
[
"Event 'new' on source-output #1",
- "Event 'new' on source-output #2",
"Event 'change' on source-output #1",
- "Event 'remove' on source-output #2",
+ "Event 'change' on source-output #1",
+ "Event 'change' on source-output #1",
"",
].join("\n")
);
- await flush();
+ await flushImmediate();
+ assert.equal(reconciles(), 2, "the first event after quiet must reconcile immediately");
- assert.equal(
- execCalls.filter(({ command }) => command === "pactl --format=json list source-outputs").length,
- 3,
- "startup reconcile plus one running and one trailing reconcile"
- );
+ t.mock.timers.tick(RECONCILE_SPACING_MS - 1);
+ await flushImmediate();
+ assert.equal(reconciles(), 2, "the rest of the burst must wait out the spacing");
+
+ t.mock.timers.tick(1);
+ await flushImmediate();
+ assert.equal(reconciles(), 3, "the last event of the burst must get a trailing reconcile");
assert.deepEqual(detector.getExternalMicState(), {
reliable: true,
externalMicActive: true,
});
+
+ t.mock.timers.tick(RECONCILE_SPACING_MS * 2);
+ await flushImmediate();
+ assert.equal(reconciles(), 3, "a finished burst must not keep reconciling");
detector.stop();
});
-test("linux: module streams without a process id stay excluded without costing reliability", async () => {
+test("linux: a single event reconciles promptly and schedules no trailing reconcile", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });
+ const { detector, children, execCalls } = createDetector("linux", {
+ execResponses: [{ stdout: "[]" }, { stdout: "[]" }],
+ });
+
+ await detector.start();
+ t.mock.timers.tick(RECONCILE_SPACING_MS);
+ children[0].stdout.emit("data", "Event 'change' on source-output #1\n");
+ await flushImmediate();
+ assert.equal(execCalls.length, 2, "a lone event must reconcile without added latency");
+
+ t.mock.timers.tick(RECONCILE_SPACING_MS * 2);
+ await flushImmediate();
+ assert.equal(execCalls.length, 2, "a lone event must not produce a ghost trailing reconcile");
+ detector.stop();
+});
+
+test("linux: an event inside the spacing window defers its reconcile to the boundary", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });
+ const { detector, children, execCalls } = createDetector("linux", {
+ execResponses: [{ stdout: "[]" }, { stdout: "[]" }],
+ });
+
+ await detector.start();
+ t.mock.timers.tick(RECONCILE_SPACING_MS / 2);
+ children[0].stdout.emit("data", "Event 'change' on source-output #1\n");
+ await flushImmediate();
+ assert.equal(execCalls.length, 1, "inside the window only the startup reconcile may have run");
+
+ t.mock.timers.tick(RECONCILE_SPACING_MS / 2);
+ await flushImmediate();
+ assert.equal(execCalls.length, 2, "the deferred reconcile must run at the spacing boundary");
+ detector.stop();
+});
+
+test("linux: module streams without a process id stay excluded without costing reliability", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });
const { detector, children } = createDetector("linux", {
excludedProcessIds: () => [700],
execResponses: [
@@ -591,16 +648,18 @@ test("linux: module streams without a process id stay excluded without costing r
detector.on("external-mic-state-changed", (state) => externalStates.push(state));
await detector.start();
+ t.mock.timers.tick(RECONCILE_SPACING_MS);
children[0].stdout.emit("data", "Event 'new' on source-output #2\n");
- await flush();
+ await flushImmediate();
assert.deepEqual(detector.getExternalMicState(), {
reliable: true,
externalMicActive: true,
});
+ t.mock.timers.tick(RECONCILE_SPACING_MS);
children[0].stdout.emit("data", "Event 'remove' on source-output #2\n");
- await flush();
+ await flushImmediate();
assert.deepEqual(detector.getExternalMicState(), {
reliable: true,
@@ -609,7 +668,8 @@ test("linux: module streams without a process id stay excluded without costing r
detector.stop();
});
-test("linux: ownership query failure is unreliable while aggregate events still prompt", async () => {
+test("linux: ownership query failure is unreliable while aggregate events still prompt", async (t) => {
+ t.mock.timers.enable({ apis: ["setTimeout", "Date"], now: 10_000 });
const { detector, children } = createDetector("linux", {
execResponses: [{ stdout: "[]" }, { stdout: "not-json" }],
});
@@ -622,8 +682,9 @@ test("linux: ownership query failure is unreliable while aggregate events still
externalMicActive: false,
});
+ t.mock.timers.tick(RECONCILE_SPACING_MS);
children[0].stdout.emit("data", "Event 'new' on source-output #7\n");
- await flush();
+ await flushImmediate();
assert.deepEqual(detector.getExternalMicState(), {
reliable: false,
diff --git a/test/helpers/gpuBinaryManager.test.js b/test/helpers/gpuBinaryManager.test.js
index f869da76c..8d49daf60 100644
--- a/test/helpers/gpuBinaryManager.test.js
+++ b/test/helpers/gpuBinaryManager.test.js
@@ -428,6 +428,54 @@ test("legacy migration: lib-free pack is moved, lib-carrying packs are cleared f
assert.equal(vulkan.isDownloaded(), true);
});
+test("orphan detection: enabled flag with no pack on disk is reported for the notice", () => {
+ const { detectOrphanedGpuPacks } = GpuBinaryManager;
+ const packs = [
+ { manager: new WhisperCudaManager(), enabledEnvVar: "WHISPER_CUDA_ENABLED" },
+ { manager: new WhisperVulkanManager(), enabledEnvVar: "WHISPER_VULKAN_ENABLED" },
+ ];
+
+ try {
+ // User never enabled GPU (missing flag) — nothing reported
+ assert.deepEqual(detectOrphanedGpuPacks(packs), []);
+
+ process.env.WHISPER_CUDA_ENABLED = "true";
+ process.env.WHISPER_VULKAN_ENABLED = "false";
+ assert.deepEqual(detectOrphanedGpuPacks(packs), ["CUDA whisper"]);
+
+ // Pack present on disk — enabled but not orphaned
+ seedPack("whisper-cuda", ["whisper-server-linux-x64-cuda"]);
+ assert.deepEqual(detectOrphanedGpuPacks(packs), []);
+
+ process.env.WHISPER_VULKAN_ENABLED = "true";
+ assert.deepEqual(detectOrphanedGpuPacks(packs), ["Vulkan whisper"]);
+
+ // The lib-carrying llama Vulkan pack (also deleted by the 1.8.3
+ // migration) is detected through the same shape
+ const llamaPacks = [
+ { manager: new LlamaVulkanManager(), enabledEnvVar: "LLAMA_VULKAN_ENABLED" },
+ ];
+ assert.deepEqual(detectOrphanedGpuPacks(llamaPacks), []);
+ process.env.LLAMA_VULKAN_ENABLED = "true";
+ assert.deepEqual(detectOrphanedGpuPacks(llamaPacks), ["Vulkan llama"]);
+ seedPack("llama-vulkan", ["llama-server-vulkan"]);
+ assert.deepEqual(detectOrphanedGpuPacks(llamaPacks), []);
+
+ // Unsupported platform can't re-download the pack — never reported
+ const unsupported = new GpuBinaryManager({ name: "none", dirName: "none", assets: {} });
+ process.env.NONE_ENABLED = "true";
+ assert.deepEqual(
+ detectOrphanedGpuPacks([{ manager: unsupported, enabledEnvVar: "NONE_ENABLED" }]),
+ []
+ );
+ } finally {
+ delete process.env.WHISPER_CUDA_ENABLED;
+ delete process.env.WHISPER_VULKAN_ENABLED;
+ delete process.env.LLAMA_VULKAN_ENABLED;
+ delete process.env.NONE_ENABLED;
+ }
+});
+
test("getStatus reflects supported/downloaded/downloading", async () => {
const manager = new WhisperVulkanManager();
assert.deepEqual(manager.getStatus(), {
diff --git a/test/helpers/gpuPackMigrationNotice.test.js b/test/helpers/gpuPackMigrationNotice.test.js
index 52ecd91dc..aac42dc6c 100644
--- a/test/helpers/gpuPackMigrationNotice.test.js
+++ b/test/helpers/gpuPackMigrationNotice.test.js
@@ -38,6 +38,30 @@ test("recording again merges and dedupes instead of overwriting", () => {
assert.deepEqual(notice.read(), { packs: ["CUDA whisper", "Vulkan llama"] });
});
+test("recordOnce fires each pack's notice only once, surviving a dismissal", () => {
+ notice.recordOnce(["CUDA whisper"]);
+ assert.deepEqual(notice.read(), { packs: ["CUDA whisper"] });
+
+ // Toast shown and dismissed; the pack is still missing on the next launch
+ notice.clear();
+ notice.recordOnce(["CUDA whisper"]);
+ assert.equal(notice.read(), null);
+
+ // A pack orphaned later still gets its one notice
+ notice.recordOnce(["CUDA whisper", "Vulkan whisper"]);
+ assert.deepEqual(notice.read(), { packs: ["Vulkan whisper"] });
+});
+
+test("recordOnce does not re-record a pack already noticed via record", () => {
+ notice.record(["CUDA whisper"]);
+ notice.recordOnce(["CUDA whisper"]);
+ assert.deepEqual(notice.read(), { packs: ["CUDA whisper"] });
+
+ notice.clear();
+ notice.recordOnce(["CUDA whisper"]);
+ assert.equal(notice.read(), null);
+});
+
test("empty recordings and corrupt sentinels read as no notice", () => {
notice.record([]);
assert.equal(notice.read(), null);
diff --git a/test/helpers/liveSpeakerIdentifier.test.js b/test/helpers/liveSpeakerIdentifier.test.js
index e4ca9a1d9..2f7ca11fd 100644
--- a/test/helpers/liveSpeakerIdentifier.test.js
+++ b/test/helpers/liveSpeakerIdentifier.test.js
@@ -39,7 +39,7 @@ function loadIdentifier(options = {}) {
MAX_EMBEDDING_SECONDS: 8,
isAvailable: () => true,
cosineSimilarity,
- extractEmbeddingFromSamples: async () => null,
+ extractEmbeddingFromSamples: options.extractEmbeddingFromSamples || (async () => null),
};
}
if (interceptsOrt && request === "onnxruntime-node") {
@@ -316,6 +316,96 @@ test("isAvailable() stays true when the binding loads", (t) => {
assert.equal(Boolean(identifier.isAvailable()), true);
});
+// onnxruntime-node defaults intra-op threads to every core with spinning
+// workers — absurd for the tiny VAD graph running ~31x/sec, and a CPU
+// regression during every meeting recording.
+test("the VAD session caps ORT to a single sequential thread", async (t) => {
+ let createArgs = null;
+ const { LiveSpeakerIdentifier, restore } = loadIdentifier({
+ ort: () => ({
+ InferenceSession: {
+ create: async (...args) => {
+ createArgs = args;
+ return { inputNames: [], outputNames: [] };
+ },
+ },
+ }),
+ });
+ t.after(restore);
+ const identifier = new LiveSpeakerIdentifier();
+ stubDownloadedModels(identifier);
+
+ assert.equal(await identifier.start(() => {}, {}), true);
+ assert.deepEqual(createArgs, [
+ __filename,
+ { intraOpNumThreads: 1, interOpNumThreads: 1, executionMode: "sequential" },
+ ]);
+});
+
+// _identifyActiveSpeechSegment runs on every speech window (~31x/sec), so its
+// gates must reject cheaply — before any chunk concat or embedding work — and
+// force must bypass only the interval gate, never the minimum-samples check.
+const LIVE_ID_MIN_SAMPLES = Math.round(16000 * 1.6);
+const LIVE_ID_INTERVAL_SAMPLES = 16000;
+const MAX_EMBEDDING_SAMPLES = 16000 * 8; // MAX_EMBEDDING_SECONDS stubbed to 8
+
+function loadIdentifierCapturingEmbeddings() {
+ const embeddingInputs = [];
+ const { LiveSpeakerIdentifier } = loadIdentifier({
+ extractEmbeddingFromSamples: async (samples) => {
+ embeddingInputs.push(samples);
+ return voiceA;
+ },
+ });
+ return { identifier: new LiveSpeakerIdentifier(), embeddingInputs };
+}
+
+test("live identification below the minimum sample count never embeds, even forced", async () => {
+ const { identifier, embeddingInputs } = loadIdentifierCapturingEmbeddings();
+ identifier.speechChunks = [new Float32Array(LIVE_ID_MIN_SAMPLES - 1)];
+ identifier.segmentEndSample = LIVE_ID_MIN_SAMPLES - 1;
+
+ await identifier._identifyActiveSpeechSegment();
+ await identifier._identifyActiveSpeechSegment(true);
+
+ assert.equal(embeddingInputs.length, 0);
+});
+
+test("the interval gate throttles repeat identification; force bypasses it", async () => {
+ const { identifier, embeddingInputs } = loadIdentifierCapturingEmbeddings();
+ identifier.speechChunks = [new Float32Array(LIVE_ID_MIN_SAMPLES)];
+ identifier.lastLiveIdentificationSample = 50000;
+ identifier.segmentEndSample = 50000 + LIVE_ID_INTERVAL_SAMPLES - 1;
+
+ await identifier._identifyActiveSpeechSegment();
+ assert.equal(embeddingInputs.length, 0, "within the interval, identification is throttled");
+
+ await identifier._identifyActiveSpeechSegment(true);
+ assert.equal(embeddingInputs.length, 1, "force must bypass the interval gate");
+ assert.equal(identifier.lastLiveIdentificationSample, identifier.segmentEndSample);
+
+ identifier.segmentEndSample += LIVE_ID_INTERVAL_SAMPLES;
+ await identifier._identifyActiveSpeechSegment();
+ assert.equal(embeddingInputs.length, 2, "once the interval elapses, identification resumes");
+});
+
+test("identification embeds the exact tail of the concatenated speech chunks", async () => {
+ const { identifier, embeddingInputs } = loadIdentifierCapturingEmbeddings();
+ const chunks = [1, 2, 3, 4].map((value) => new Float32Array(40000).fill(value));
+ identifier.speechChunks = chunks;
+ identifier.segmentEndSample = 160000;
+
+ await identifier._identifyActiveSpeechSegment();
+
+ const flat = new Float32Array(160000);
+ chunks.forEach((chunk, i) => flat.set(chunk, i * 40000));
+ assert.deepEqual(
+ embeddingInputs[0],
+ flat.subarray(flat.length - MAX_EMBEDDING_SAMPLES),
+ "the embedding window must stay byte-identical to the pre-fix concat + slice"
+ );
+});
+
test("distinct voices are folded into one cluster when the session cap is 1", () => {
const { LiveSpeakerIdentifier } = loadIdentifier();
const identifier = new LiveSpeakerIdentifier();
diff --git a/test/helpers/qdrantManager.test.js b/test/helpers/qdrantManager.test.js
new file mode 100644
index 000000000..1ec53243b
--- /dev/null
+++ b/test/helpers/qdrantManager.test.js
@@ -0,0 +1,371 @@
+const test = require("node:test");
+const { afterEach } = require("node:test");
+const assert = require("node:assert/strict");
+const Module = require("node:module");
+const { EventEmitter } = require("node:events");
+
+const managerModulePath = require.resolve("../../src/helpers/qdrantManager");
+const originalLoad = Module._load;
+
+const HEALTH_CHECK_INTERVAL_MS = 5000;
+
+function flushPromises() {
+ return new Promise((resolve) => setImmediate(resolve));
+}
+
+function makeChild(pid) {
+ const child = new EventEmitter();
+ child.pid = pid;
+ child.exitCode = null;
+ child.killed = false;
+ child.stdout = new EventEmitter();
+ child.stderr = new EventEmitter();
+ child.kill = () => {
+ child.killed = true;
+ };
+ return child;
+}
+
+// Loads a fresh QdrantManager with spawn, http health checks, pid-file
+// bookkeeping, and process teardown all stubbed, so tests can wedge and
+// recover the sidecar without real processes or sockets.
+function loadManager({ gracefulStop } = {}) {
+ delete require.cache[managerModulePath];
+
+ const state = {
+ healthy: true,
+ spawnCalls: [],
+ pidFileOps: [],
+ warns: [],
+ errors: [],
+ waitForExitResult: true,
+ nextPid: 1001,
+ failNextFindPort: false,
+ portGate: null,
+ };
+
+ const defaultGracefulStop = async (proc) => {
+ proc.exitCode = 0;
+ proc.emit("close", 0);
+ };
+
+ Module._load = function loadWithMocks(request, parent, isMain) {
+ if (request === "./debugLogger") {
+ return {
+ debug() {},
+ info() {},
+ warn: (msg, meta) => state.warns.push({ msg, meta }),
+ error: (msg, meta) => state.errors.push({ msg, meta }),
+ };
+ }
+ if (request === "child_process") {
+ return {
+ spawn: () => {
+ const child = makeChild(state.nextPid++);
+ state.spawnCalls.push(child);
+ return child;
+ },
+ };
+ }
+ if (request === "http") {
+ return {
+ request: (options, onResponse) => {
+ const req = new EventEmitter();
+ req.destroy = () => {};
+ req.end = () => {
+ queueMicrotask(() => {
+ if (state.healthy) onResponse({ resume() {} });
+ else req.emit("error", new Error("connect ECONNREFUSED"));
+ });
+ };
+ return req;
+ },
+ };
+ }
+ if (request === "fs") {
+ return { mkdirSync() {}, writeFileSync() {} };
+ }
+ if (request === "../utils/serverUtils") {
+ return {
+ findAvailablePort: async () => {
+ if (state.failNextFindPort) {
+ state.failNextFindPort = false;
+ throw new Error("no ports");
+ }
+ if (state.portGate) await state.portGate;
+ return 6333;
+ },
+ resolveBinaryPath: () => "/fake/bin/qdrant",
+ gracefulStopProcess: (proc) => (gracefulStop || defaultGracefulStop)(proc),
+ };
+ }
+ if (request === "./sidecarPidFile") {
+ return {
+ write: (name, pid) => state.pidFileOps.push(["write", name, pid]),
+ clear: (name) => state.pidFileOps.push(["clear", name]),
+ };
+ }
+ if (request === "./sidecarReaper") {
+ return { waitForExit: async () => state.waitForExitResult };
+ }
+ return originalLoad(request, parent, isMain);
+ };
+
+ try {
+ const QdrantManager = require(managerModulePath);
+ return { QdrantManager, manager: new QdrantManager(), state };
+ } finally {
+ Module._load = originalLoad;
+ }
+}
+
+afterEach(() => {
+ Module._load = originalLoad;
+});
+
+async function tickHealthCheck(t, times) {
+ for (let i = 0; i < times; i++) {
+ t.mock.timers.tick(HEALTH_CHECK_INTERVAL_MS);
+ await flushPromises();
+ }
+}
+
+// setTimeout stays real (only setInterval is mocked), so the restart's
+// startup polling and this wait both run on real time.
+async function waitForReady(manager, timeoutMs = 3000) {
+ const deadline = Date.now() + timeoutMs;
+ while (!manager.isReady() && Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ }
+ return manager.isReady();
+}
+
+test("start spawns qdrant, writes the pid entry, and stop clears it", async () => {
+ const { manager, state } = loadManager();
+
+ await manager.start();
+
+ assert.equal(manager.isReady(), true);
+ assert.equal(manager.getPort(), 6333);
+ assert.deepEqual(state.pidFileOps, [["write", "qdrant", 1001]]);
+
+ await manager.stop();
+
+ assert.equal(manager.isReady(), false);
+ assert.equal(manager.getStatus().running, false);
+ assert.deepEqual(state.pidFileOps[state.pidFileOps.length - 1], ["clear", "qdrant"]);
+});
+
+test("restarts the sidecar after sustained health-check failures", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ const { QdrantManager, manager, state } = loadManager();
+ await manager.start();
+
+ state.healthy = false;
+ await tickHealthCheck(t, QdrantManager.HEALTH_FAILURES_BEFORE_RESTART);
+ state.healthy = true;
+
+ assert.equal(await waitForReady(manager), true);
+ assert.equal(state.spawnCalls.length, 2);
+ assert.equal(manager.getPort(), 6333);
+ assert.deepEqual(state.pidFileOps, [
+ ["write", "qdrant", 1001],
+ ["clear", "qdrant"],
+ ["write", "qdrant", 1002],
+ ]);
+
+ // The replacement is monitored again and healthy checks keep it alone.
+ await tickHealthCheck(t, 2);
+ assert.equal(state.spawnCalls.length, 2);
+});
+
+test("a healthy check resets the consecutive-failure count", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ const { QdrantManager, manager, state } = loadManager();
+ await manager.start();
+ const belowThreshold = QdrantManager.HEALTH_FAILURES_BEFORE_RESTART - 1;
+
+ state.healthy = false;
+ await tickHealthCheck(t, belowThreshold);
+ state.healthy = true;
+ await tickHealthCheck(t, 1);
+ state.healthy = false;
+ await tickHealthCheck(t, belowThreshold);
+
+ assert.equal(state.spawnCalls.length, 1, "should never have restarted");
+});
+
+test("stays stopped with one warning once the restart budget is spent", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ const { QdrantManager, manager, state } = loadManager();
+ await manager.start();
+
+ manager.restartCount = QdrantManager.MAX_RESTARTS_PER_SESSION;
+ state.healthy = false;
+ await tickHealthCheck(t, QdrantManager.HEALTH_FAILURES_BEFORE_RESTART);
+
+ assert.equal(state.spawnCalls.length, 1);
+ assert.equal(manager.isReady(), false);
+ assert.equal(manager.getStatus().running, false);
+ assert.equal(manager.healthCheckInterval, null);
+ const giveUpWarns = state.warns.filter(({ msg }) => msg.includes("max restarts"));
+ assert.equal(giveUpWarns.length, 1);
+
+ // The interval is gone, so nothing keeps retrying.
+ await tickHealthCheck(t, 2);
+ assert.equal(state.spawnCalls.length, 1);
+});
+
+test("a failed restart leaves qdrant stopped instead of crash-looping", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ const { QdrantManager, manager, state } = loadManager();
+ await manager.start();
+
+ state.healthy = false;
+ state.failNextFindPort = true;
+ await tickHealthCheck(t, QdrantManager.HEALTH_FAILURES_BEFORE_RESTART);
+
+ assert.equal(state.spawnCalls.length, 1);
+ assert.equal(manager.isReady(), false);
+ assert.equal(manager.healthCheckInterval, null);
+ const failWarns = state.warns.filter(({ msg }) => msg.includes("restart failed"));
+ assert.equal(failWarns.length, 1);
+});
+
+test("a restart whose replacement never becomes healthy is stopped, not orphaned", async (t) => {
+ // Date + setTimeout are mocked so the replacement's 30s startup timeout can
+ // be driven without real waiting (flushPromises stays real via setImmediate).
+ t.mock.timers.enable({ apis: ["setInterval", "setTimeout", "Date"] });
+ const stoppedPids = [];
+ const { QdrantManager, manager, state } = loadManager({
+ gracefulStop: async (proc) => {
+ stoppedPids.push(proc.pid);
+ proc.exitCode = 0;
+ proc.emit("close", 0);
+ },
+ });
+ await manager.start();
+
+ state.healthy = false;
+ await tickHealthCheck(t, QdrantManager.HEALTH_FAILURES_BEFORE_RESTART);
+
+ // The replacement spawned but stays unhealthy; tick it past the timeout.
+ assert.equal(state.spawnCalls.length, 2);
+ for (let i = 0; i < 10 && !state.warns.some(({ msg }) => msg.includes("restart failed")); i++) {
+ await tickHealthCheck(t, 1);
+ }
+
+ assert.equal(state.warns.filter(({ msg }) => msg.includes("restart failed")).length, 1);
+ assert.deepEqual(stoppedPids, [1001, 1002], "the failed replacement must be stopped too");
+ assert.equal(manager.getStatus().running, false);
+ assert.deepEqual(state.pidFileOps[state.pidFileOps.length - 1], ["clear", "qdrant"]);
+});
+
+test("a stop during the restart's pre-spawn port scan aborts without spawning", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ const { QdrantManager, manager, state } = loadManager();
+ await manager.start();
+
+ let releasePort;
+ state.portGate = new Promise((resolve) => {
+ releasePort = resolve;
+ });
+ state.healthy = false;
+ await tickHealthCheck(t, QdrantManager.HEALTH_FAILURES_BEFORE_RESTART);
+
+ // The restart already killed the old process and is awaiting the port scan,
+ // so this quit's stop finds nothing to kill.
+ await manager.stop();
+ releasePort();
+ await flushPromises();
+ await flushPromises();
+
+ assert.equal(state.spawnCalls.length, 1, "no replacement may spawn after quit");
+ assert.equal(manager.getStatus().running, false);
+ assert.equal(manager.getPort(), null);
+});
+
+test("a successful unhealthy-restart emits 'restarted' with the new port", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ const { QdrantManager, manager, state } = loadManager();
+ const restartedPorts = [];
+ manager.on("restarted", (port) => restartedPorts.push(port));
+ await manager.start();
+
+ state.healthy = false;
+ await tickHealthCheck(t, QdrantManager.HEALTH_FAILURES_BEFORE_RESTART);
+ state.healthy = true;
+
+ assert.equal(await waitForReady(manager), true);
+ await flushPromises();
+ assert.deepEqual(restartedPorts, [6333]);
+});
+
+test("does not respawn over a process that survived SIGKILL", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ const { QdrantManager, manager, state } = loadManager({ gracefulStop: async () => {} });
+ await manager.start();
+
+ state.healthy = false;
+ state.waitForExitResult = false;
+ await tickHealthCheck(t, QdrantManager.HEALTH_FAILURES_BEFORE_RESTART);
+
+ assert.equal(state.spawnCalls.length, 1);
+ assert.equal(manager.getStatus().running, false);
+ // The pid entry is restored so the next launch's reaper retries the kill.
+ assert.deepEqual(state.pidFileOps[state.pidFileOps.length - 1], ["write", "qdrant", 1001]);
+ assert.equal(state.errors.filter(({ msg }) => msg.includes("survived SIGKILL")).length, 1);
+});
+
+test("an app-quit stop during a restart wins and nothing respawns", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ let releaseStop;
+ const gate = new Promise((resolve) => {
+ releaseStop = resolve;
+ });
+ const { QdrantManager, manager, state } = loadManager({
+ gracefulStop: async (proc) => {
+ await gate;
+ proc.exitCode = 0;
+ proc.emit("close", 0);
+ },
+ });
+ await manager.start();
+
+ state.healthy = false;
+ await tickHealthCheck(t, QdrantManager.HEALTH_FAILURES_BEFORE_RESTART);
+
+ // The restart is blocked inside its stop when the app quits.
+ const quitStop = manager.stop();
+ releaseStop();
+ await quitStop;
+ await flushPromises();
+ await flushPromises();
+
+ assert.equal(state.spawnCalls.length, 1);
+ assert.equal(manager.getStatus().running, false);
+ assert.equal(manager.healthCheckInterval, null);
+});
+
+test("a late close from the replaced child does not clobber the new process", async (t) => {
+ t.mock.timers.enable({ apis: ["setInterval"] });
+ // gracefulStopProcess resolving without a close is the SIGKILL escalation
+ // path: the wedged child dies (and emits close) only later.
+ const { QdrantManager, manager, state } = loadManager({ gracefulStop: async () => {} });
+ await manager.start();
+ const wedgedChild = state.spawnCalls[0];
+
+ state.healthy = false;
+ await tickHealthCheck(t, QdrantManager.HEALTH_FAILURES_BEFORE_RESTART);
+ state.healthy = true;
+ assert.equal(await waitForReady(manager), true);
+ assert.equal(state.spawnCalls.length, 2);
+ const opsBeforeLateClose = state.pidFileOps.length;
+
+ wedgedChild.emit("close", null);
+
+ assert.equal(manager.isReady(), true);
+ assert.equal(manager.getStatus().running, true);
+ assert.notEqual(manager.healthCheckInterval, null);
+ assert.equal(state.pidFileOps.length, opsBeforeLateClose, "pid entry must not be cleared");
+});
diff --git a/test/helpers/sidecarReaper.test.js b/test/helpers/sidecarReaper.test.js
index bbb38a29d..9a090c701 100644
--- a/test/helpers/sidecarReaper.test.js
+++ b/test/helpers/sidecarReaper.test.js
@@ -17,7 +17,7 @@ require.cache[electronPath] = {
};
const sidecarPidFile = require("../../src/helpers/sidecarPidFile");
-const { reapStaleSidecars } = require("../../src/helpers/sidecarReaper");
+const { reapStaleSidecars, waitForExit } = require("../../src/helpers/sidecarReaper");
// Short graces keep the escalation path fast; the poll interval is 200ms so
// anything comfortably above that works.
@@ -103,6 +103,18 @@ test("does not kill a reused PID that is no longer the sidecar binary", posixOnl
assert.deepEqual(sidecarPidFile.readAll(), []);
});
+// qdrantManager's unhealthy-restart path uses waitForExit to verify the old
+// process is gone before spawning a replacement.
+test("waitForExit distinguishes a live process from a dead one", async (t) => {
+ createUserDataDir(t);
+ const child = await spawnFakeSidecar(t, { scriptName: "qdrant-wait.js", ignoreSigterm: false });
+
+ assert.equal(await waitForExit(child.pid, 400), false);
+
+ process.kill(child.pid, "SIGKILL");
+ assert.equal(await waitForExit(child.pid, 2000), true);
+});
+
test("clears entries for processes that already exited", async (t) => {
createUserDataDir(t);
const child = await spawnFakeSidecar(t, { scriptName: "qdrant-gone.js", ignoreSigterm: false });
diff --git a/test/helpers/whisperGpuUpgradeReset.test.js b/test/helpers/whisperGpuUpgradeReset.test.js
new file mode 100644
index 000000000..e71936577
--- /dev/null
+++ b/test/helpers/whisperGpuUpgradeReset.test.js
@@ -0,0 +1,129 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+const fs = require("fs");
+const os = require("os");
+const path = require("path");
+
+// Runs outside Electron: stub the app userData path and version before loading.
+let userDataDir = null;
+let appVersion = "1.9.1";
+
+require.cache[require.resolve("electron")] = {
+ exports: { app: { getPath: () => userDataDir, getVersion: () => appVersion } },
+};
+
+const { resetWhisperGpuFailureOnUpgrade } = require("../../src/helpers/whisperGpuUpgradeReset.js");
+
+function makeEnvManager() {
+ const manager = { removals: [] };
+ manager.removeKeyFromEnvFile = async (key) => {
+ manager.removals.push(key);
+ };
+ return manager;
+}
+
+test.beforeEach(() => {
+ userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), "gpu-upgrade-reset-"));
+ appVersion = "1.9.1";
+ delete process.env.WHISPER_GPU_FAILED;
+});
+
+test.afterEach(() => {
+ fs.rmSync(userDataDir, { recursive: true, force: true });
+ delete process.env.WHISPER_GPU_FAILED;
+});
+
+test("clears the remembered GPU failure exactly once per version change", () => {
+ process.env.WHISPER_GPU_FAILED = "cuda";
+ const envManager = makeEnvManager();
+
+ // First launch of this version (no sentinel yet, e.g. upgrading from 1.8.3)
+ assert.equal(resetWhisperGpuFailureOnUpgrade(envManager), true);
+ assert.equal(process.env.WHISPER_GPU_FAILED, undefined);
+ assert.deepEqual(envManager.removals, ["WHISPER_GPU_FAILED"]);
+
+ // GPU failed again on this version — the flag survives relaunches
+ process.env.WHISPER_GPU_FAILED = "cuda";
+ assert.equal(resetWhisperGpuFailureOnUpgrade(envManager), false);
+ assert.equal(process.env.WHISPER_GPU_FAILED, "cuda");
+ assert.equal(envManager.removals.length, 1);
+
+ // The next upgrade earns one more fresh attempt
+ appVersion = "1.9.2";
+ assert.equal(resetWhisperGpuFailureOnUpgrade(envManager), true);
+ assert.equal(process.env.WHISPER_GPU_FAILED, undefined);
+ assert.equal(envManager.removals.length, 2);
+});
+
+test("records the running version without persisting when no failure is stored", () => {
+ const envManager = makeEnvManager();
+ assert.equal(resetWhisperGpuFailureOnUpgrade(envManager), false);
+ assert.deepEqual(envManager.removals, []);
+
+ // The sentinel now pins this version: a failure recorded later on it sticks
+ process.env.WHISPER_GPU_FAILED = "vulkan";
+ assert.equal(resetWhisperGpuFailureOnUpgrade(envManager), false);
+ assert.equal(process.env.WHISPER_GPU_FAILED, "vulkan");
+ assert.deepEqual(envManager.removals, []);
+});
+
+test("reset removes only the WHISPER_GPU_FAILED line; hand-added .env lines survive", async () => {
+ // Real EnvironmentManager (electron already stubbed above; dotenv stubbed and
+ // resourcesPath pinned) so the on-disk .env edit is pinned, not a stub.
+ const dotenvPath = require.resolve("dotenv");
+ const originalDotenv = require.cache[dotenvPath];
+ require.cache[dotenvPath] = {
+ id: dotenvPath,
+ filename: dotenvPath,
+ loaded: true,
+ exports: { config: () => ({ parsed: {} }) },
+ };
+ const originalResourcesPath = process.resourcesPath;
+ process.resourcesPath = userDataDir;
+
+ try {
+ const EnvironmentManager = require("../../src/helpers/environment.js");
+ const envPath = path.join(userDataDir, ".env");
+ fs.writeFileSync(
+ envPath,
+ [
+ "# OpenWhispr Environment Variables",
+ "OPENWHISPR_LOG_LEVEL=debug", // hand-added: not in PERSISTED_KEYS
+ "WHISPER_GPU_FAILED=cuda",
+ "WHISPER_CUDA_ENABLED=true",
+ "",
+ ].join("\n")
+ );
+ process.env.WHISPER_GPU_FAILED = "cuda";
+
+ const envManager = new EnvironmentManager();
+ const realRemove = envManager.removeKeyFromEnvFile.bind(envManager);
+ let persistence = null;
+ envManager.removeKeyFromEnvFile = (key) => (persistence = realRemove(key));
+
+ assert.equal(resetWhisperGpuFailureOnUpgrade(envManager), true);
+ assert.equal(process.env.WHISPER_GPU_FAILED, undefined);
+ assert.ok(persistence);
+ await persistence;
+
+ assert.equal(
+ fs.readFileSync(envPath, "utf8"),
+ [
+ "# OpenWhispr Environment Variables",
+ "OPENWHISPR_LOG_LEVEL=debug",
+ "WHISPER_CUDA_ENABLED=true",
+ "",
+ ].join("\n"),
+ "every line except WHISPER_GPU_FAILED is preserved verbatim"
+ );
+
+ // A missing .env is tolerated (fresh install: nothing to remove)
+ fs.unlinkSync(envPath);
+ await envManager.removeKeyFromEnvFile("WHISPER_GPU_FAILED");
+ assert.equal(fs.existsSync(envPath), false);
+ } finally {
+ if (originalDotenv) require.cache[dotenvPath] = originalDotenv;
+ else delete require.cache[dotenvPath];
+ process.resourcesPath = originalResourcesPath;
+ }
+});
diff --git a/test/helpers/whisperServerGpuGuard.test.js b/test/helpers/whisperServerGpuGuard.test.js
new file mode 100644
index 000000000..69ab627f1
--- /dev/null
+++ b/test/helpers/whisperServerGpuGuard.test.js
@@ -0,0 +1,195 @@
+const test = require("node:test");
+const assert = require("node:assert/strict");
+
+const WhisperServerManager = require("../../src/helpers/whisperServer");
+const { getGpuSignature } = WhisperServerManager;
+
+// start()'s no-op guard must include the GPU backend: before #1458's hotfix a
+// running CPU server silently ignored later GPU-enabled start requests
+// (sticky-CPU), while a genuine GPU->CPU fallback must NOT restart-loop —
+// WHISPER_GPU_FAILED makes the next request resolve to CPU, matching the
+// fallback server's actual (CPU) signature.
+
+const ENV_KEYS = ["WHISPER_VULKAN_DEVICE"];
+const saved = {};
+
+test.beforeEach(() => {
+ for (const key of ENV_KEYS) {
+ saved[key] = process.env[key];
+ delete process.env[key];
+ }
+});
+
+test.afterEach(() => {
+ for (const key of ENV_KEYS) {
+ if (saved[key] === undefined) delete process.env[key];
+ else process.env[key] = saved[key];
+ }
+});
+
+test("getGpuSignature resolves the backend the way _doStart does", () => {
+ assert.equal(getGpuSignature({}), "gpu:cpu");
+ assert.equal(getGpuSignature({ useCuda: true }), "gpu:cuda");
+ assert.equal(getGpuSignature({ useVulkan: true }), "gpu:vulkan:default");
+ // CUDA wins when both flags are set, mirroring _doStart's resolution.
+ assert.equal(getGpuSignature({ useCuda: true, useVulkan: true }), "gpu:cuda");
+});
+
+test("getGpuSignature carries the resolved Vulkan device pin", () => {
+ assert.equal(getGpuSignature({ useVulkan: true, vulkanDeviceIndex: 1 }), "gpu:vulkan:1");
+
+ process.env.WHISPER_VULKAN_DEVICE = "2";
+ assert.equal(getGpuSignature({ useVulkan: true }), "gpu:vulkan:2");
+ // An explicit -1 means "explicitly unpinned": the stale env pin must not resurface.
+ assert.equal(getGpuSignature({ useVulkan: true, vulkanDeviceIndex: -1 }), "gpu:vulkan:default");
+ // The pin is irrelevant off Vulkan.
+ assert.equal(getGpuSignature({ useCuda: true }), "gpu:cuda");
+ assert.equal(getGpuSignature({}), "gpu:cpu");
+});
+
+test("the CPU-fallback recursion signature matches a fresh CPU-resolved request", () => {
+ // _doStart's GPU catch recurses with { useCuda: false, useVulkan: false };
+ // after the failure is recorded, resolveGpuStartOptions() yields the same
+ // flags — equal signatures are what keep a fallback session stable.
+ assert.equal(
+ getGpuSignature({ useCuda: false, useVulkan: false, vulkanDeviceIndex: 3 }),
+ getGpuSignature({})
+ );
+});
+
+test("the one-shot pin restart signature matches the next request once the pin persists", () => {
+ const pinnedRestart = getGpuSignature({ useVulkan: true, vulkanDeviceIndex: 1 });
+ process.env.WHISPER_VULKAN_DEVICE = "1";
+ assert.equal(getGpuSignature({ useVulkan: true }), pinnedRestart);
+});
+
+test("the pin-clear restart signature matches the next request once the env pin is removed", () => {
+ const clearedRestart = getGpuSignature({ useVulkan: true, vulkanDeviceIndex: -1 });
+ delete process.env.WHISPER_VULKAN_DEVICE;
+ assert.equal(getGpuSignature({ useVulkan: true }), clearedRestart);
+});
+
+function createManager() {
+ const manager = new WhisperServerManager();
+ const doStartCalls = [];
+ // Mirror the real _doStart contract: on success the actual flags and the
+ // gpu signature track what this start runs.
+ manager._doStart = async (modelPath, options) => {
+ doStartCalls.push({ modelPath, options });
+ manager.modelPath = modelPath;
+ manager.useCuda = options.useCuda === true;
+ manager.useVulkan = !manager.useCuda && options.useVulkan === true;
+ manager.gpuSignature = getGpuSignature(options);
+ manager.process = {};
+ manager.ready = true;
+ };
+ manager.stop = async () => {
+ manager.process = null;
+ manager.ready = false;
+ manager.modelPath = null;
+ // Mirror the real stop() contract: an explicit stop clears the in-session
+ // CPU pin so the next start gets a fresh GPU attempt.
+ manager.gpuFallbackActive = false;
+ };
+ return { manager, doStartCalls };
+}
+
+// Emulate _doStart's real GPU catch: the requested GPU server died during
+// startup, so stop, mark the in-session fallback, and recurse with the
+// corrected CPU flags. failVulkan=false models a working Vulkan pack next to
+// a broken CUDA one.
+function emulateGpuStartupFallback(manager, { failVulkan = true } = {}) {
+ const contractDoStart = manager._doStart;
+ manager._doStart = async (modelPath, options) => {
+ const usingCuda = options.useCuda === true;
+ const usingVulkan = !usingCuda && options.useVulkan === true;
+ if (usingCuda || (usingVulkan && failVulkan)) {
+ await manager.stop();
+ manager.gpuFallbackActive = true;
+ return manager._doStart(modelPath, { ...options, useCuda: false, useVulkan: false });
+ }
+ return contractDoStart(modelPath, options);
+ };
+}
+
+test("an identical repeat start() still no-ops", async () => {
+ const { manager, doStartCalls } = createManager();
+
+ await manager.start("/tmp/model.bin", {});
+ await manager.start("/tmp/model.bin", {});
+ assert.equal(doStartCalls.length, 1);
+
+ const gpu = createManager();
+ await gpu.manager.start("/tmp/model.bin", { useCuda: true });
+ await gpu.manager.start("/tmp/model.bin", { useCuda: true });
+ assert.equal(gpu.doStartCalls.length, 1);
+});
+
+test("a GPU-enabled request restarts a running CPU server (newly-downloaded pack)", async () => {
+ const { manager, doStartCalls } = createManager();
+
+ await manager.start("/tmp/model.bin", { useCuda: false, useVulkan: false });
+ assert.equal(doStartCalls.length, 1);
+
+ // The pack finished downloading: resolveGpuStartOptions() now requests CUDA.
+ await manager.start("/tmp/model.bin", { useCuda: true, useVulkan: false });
+ assert.equal(doStartCalls.length, 2);
+ assert.equal(doStartCalls[1].options.useCuda, true);
+ assert.equal(manager.useCuda, true);
+
+ const vulkan = createManager();
+ await vulkan.manager.start("/tmp/model.bin", { useCuda: false, useVulkan: false });
+ await vulkan.manager.start("/tmp/model.bin", { useCuda: false, useVulkan: true });
+ assert.equal(vulkan.doStartCalls.length, 2);
+ assert.equal(vulkan.manager.useVulkan, true);
+});
+
+test("a fallback session stays stable: CPU-resolved requests no-op after a GPU->CPU fallback", async () => {
+ const { manager, doStartCalls } = createManager();
+ emulateGpuStartupFallback(manager);
+
+ await manager.start("/tmp/model.bin", { useCuda: true });
+ assert.equal(doStartCalls.length, 1);
+ assert.equal(manager.useCuda, false);
+ assert.equal(manager.gpuSignature, "gpu:cpu");
+
+ // WHISPER_GPU_FAILED was recorded on the fallback event, so the next
+ // dictation resolves to CPU — the guard must not restart the CPU server.
+ await manager.start("/tmp/model.bin", { useCuda: false, useVulkan: false });
+ assert.equal(doStartCalls.length, 1);
+});
+
+test("a fallback session pins CPU: a Vulkan-resolved request no-ops after a CUDA->CPU fallback", async () => {
+ const { manager, doStartCalls } = createManager();
+ emulateGpuStartupFallback(manager, { failVulkan: false });
+
+ await manager.start("/tmp/model.bin", { useCuda: true });
+ assert.equal(doStartCalls.length, 1);
+ assert.equal(manager.gpuSignature, "gpu:cpu");
+ const cpuServer = manager.process;
+
+ // Both packs installed: WHISPER_GPU_FAILED only records cuda, so the next
+ // dictation resolves to Vulkan. The in-session pin must keep the working
+ // CPU server instead of tearing it down for a Vulkan cold start.
+ await manager.start("/tmp/model.bin", { useCuda: false, useVulkan: true });
+ assert.equal(doStartCalls.length, 1);
+ assert.equal(manager.process, cpuServer);
+ assert.equal(manager.useVulkan, false);
+});
+
+test("an explicit stop() lifts the CPU pin: the next GPU-resolved start engages the GPU", async () => {
+ const { manager, doStartCalls } = createManager();
+ emulateGpuStartupFallback(manager, { failVulkan: false });
+
+ await manager.start("/tmp/model.bin", { useCuda: true });
+ assert.equal(doStartCalls.length, 1);
+ assert.equal(manager.gpuSignature, "gpu:cpu");
+
+ // restartServerWithGpuPreference (pack download, explicit Retry, delete)
+ // stops first — that clears the pin and re-attempts GPU.
+ await manager.stop();
+ await manager.start("/tmp/model.bin", { useCuda: false, useVulkan: true });
+ assert.equal(doStartCalls.length, 2);
+ assert.equal(manager.useVulkan, true);
+ assert.equal(manager.gpuSignature, "gpu:vulkan:default");
+});
diff --git a/test/helpers/whisperServerInferenceFields.test.js b/test/helpers/whisperServerInferenceFields.test.js
index a6bd4f602..0173363c2 100644
--- a/test/helpers/whisperServerInferenceFields.test.js
+++ b/test/helpers/whisperServerInferenceFields.test.js
@@ -3,6 +3,7 @@ const assert = require("node:assert/strict");
const http = require("node:http");
const WhisperServerManager = require("../../src/helpers/whisperServer");
+const WhisperManager = require("../../src/helpers/whisper");
const { INFERENCE_DECODER_FIELDS } = WhisperServerManager;
function startCapturingServer() {
@@ -97,3 +98,44 @@ test("sends the decoder threshold fields even without an initial prompt", async
assert.equal(fieldValue(body, "prompt"), null);
assert.equal(fieldValue(body, "response_format"), "json");
});
+
+test("skipDecoderThresholds omits the raised fields so the server keeps its defaults", async (t) => {
+ const { server, port, getBody } = await startCapturingServer();
+ t.after(() => server.close());
+
+ const manager = createManager(port);
+ const result = await manager.transcribe(Buffer.from("audio"), {
+ language: "en",
+ skipDecoderThresholds: true,
+ });
+ assert.equal(result.text, "ok");
+
+ const body = getBody();
+ for (const name of Object.keys(INFERENCE_DECODER_FIELDS)) {
+ assert.equal(fieldValue(body, name), null, `expected ${name} to be omitted`);
+ }
+ assert.equal(fieldValue(body, "language"), "en");
+ assert.equal(fieldValue(body, "response_format"), "json");
+});
+
+test("transcribeLocalWhisper plumbs skipDecoderThresholds to the server request (meeting chunks)", async () => {
+ const manager = new WhisperManager();
+ const captured = [];
+ manager.serverManager.isAvailable = () => true;
+ manager.serverManager.start = async () => {};
+ manager.serverManager.transcribe = async (_buffer, options) => {
+ captured.push(options);
+ return { text: "ok" };
+ };
+ manager.getModelPath = () => __filename;
+
+ await manager.transcribeLocalWhisper(Buffer.from("audio"), {
+ model: "base",
+ skipDecoderThresholds: true,
+ });
+ assert.equal(captured[0].skipDecoderThresholds, true);
+
+ // Every caller that does not opt out (dictation, note uploads) keeps the raised fields.
+ await manager.transcribeLocalWhisper(Buffer.from("audio"), { model: "base" });
+ assert.equal(captured[1].skipDecoderThresholds, false);
+});