Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(ui): prewarm voice capture startup (#2943)

Call White3151b5612887
diff --git a/ui/src/components/workbench/Composer.tsx b/ui/src/components/workbench/Composer.tsx
index 8b59211fe..1530843c4 100644
--- a/ui/src/components/workbench/Composer.tsx
+++ b/ui/src/components/workbench/Composer.tsx
@@ -47,6 +47,7 @@ import {
claimVoiceCapture,
deleteMapValueIfCurrent,
isVoiceControlDisabled,
+ prewarmVoiceCapture,
type VoiceCaptureClaim,
VoiceRecordingPipeline,
} from '../../lib/voiceRecording';
@@ -586,6 +587,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
// paired + enabled), so it never dead-ends on click.
useEffect(() => {
if (!mediaEnabled) return;
+ // Prepare the AudioWorklet while the Chat page is idle. No microphone is
+ // opened here; this only removes worklet compilation from the first word.
+ void prewarmVoiceCapture().catch(() => undefined);
let alive = true;
apiFetch('/api/asr/status')
.then((res) => (res.ok ? res.json() : null))
@@ -1082,6 +1086,9 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
};
}
const reply = readLatestAgentReply?.();
+ // Start compiling the capture graph in parallel with the permission and
+ // lock steps. The microphone is still requested only by getUserMedia below.
+ void prewarmVoiceCapture().catch(() => undefined);
recordingStartRef.current = true;
setRecordingStarting(true);
let stream: MediaStream | null = null;
@@ -1631,6 +1638,7 @@ export const Composer = forwardRef<ComposerHandle, ComposerProps>(function Compo
variant="ghost"
size="icon"
onPointerDown={() => {
+ void prewarmVoiceCapture().catch(() => undefined);
pendingVoiceInsertionRef.current = captureVoiceInsertion();
}}
onPointerCancel={() => {
diff --git a/ui/src/lib/voiceRecording.test.ts b/ui/src/lib/voiceRecording.test.ts
index 141d731a3..d84d5a249 100644
--- a/ui/src/lib/voiceRecording.test.ts
+++ b/ui/src/lib/voiceRecording.test.ts
@@ -4,6 +4,7 @@ import {
claimVoiceCapture,
deleteMapValueIfCurrent,
isVoiceControlDisabled,
+ prewarmVoiceCapture,
VOICE_CAPTURE_STOP_TIMEOUT_MS,
VOICE_MIN_SEGMENT_MS,
voicePcmDeliverySamples,
@@ -348,6 +349,82 @@ describe('VoiceRecordingPipeline', () => {
expect(onStopped).toHaveBeenCalledWith('finish', { pendingSegmentCount: 0 });
});
+ it('reuses a prewarmed audio context and retries gesture-gated resume', async () => {
+ const addModule = vi.fn(async () => undefined);
+ class FakeAudioContext {
+ static instance: FakeAudioContext | null = null;
+ state = 'suspended';
+ readonly audioWorklet = { addModule };
+ readonly destination = {};
+ readonly close = vi.fn(async () => {
+ this.state = 'closed';
+ });
+ readonly resume = vi.fn(async () => undefined);
+ readonly createMediaStreamSource = vi.fn(() => ({
+ connect: vi.fn(),
+ disconnect: vi.fn(),
+ }));
+
+ constructor() {
+ FakeAudioContext.instance = this;
+ }
+ }
+ class FakeAudioWorkletNode {
+ static instance: FakeAudioWorkletNode | null = null;
+ readonly port = {
+ onmessage: null as ((event: {
+ data: { type?: string; samples?: ArrayBuffer };
+ }) => void) | null,
+ postMessage: vi.fn(),
+ close: vi.fn(),
+ };
+ onprocessorerror: (() => void) | null = null;
+ readonly connect = vi.fn();
+ readonly disconnect = vi.fn();
+
+ constructor() {
+ FakeAudioWorkletNode.instance = this;
+ }
+ }
+ const track = new EventTarget() as EventTarget & {
+ readyState: MediaStreamTrackState;
+ stop: ReturnType<typeof vi.fn>;
+ };
+ track.readyState = 'live';
+ track.stop = vi.fn();
+ const stream = { getTracks: () => [track] } as unknown as MediaStream;
+ const onStopped = vi.fn();
+ vi.stubGlobal('AudioContext', FakeAudioContext);
+ vi.stubGlobal('AudioWorkletNode', FakeAudioWorkletNode);
+ vi.stubGlobal('URL', {
+ createObjectURL: vi.fn(() => 'blob:voice-worklet'),
+ revokeObjectURL: vi.fn(),
+ });
+
+ await prewarmVoiceCapture();
+ expect(FakeAudioContext.instance?.resume).toHaveBeenCalledOnce();
+ await prewarmVoiceCapture();
+ expect(FakeAudioContext.instance?.resume).toHaveBeenCalledTimes(2);
+ const pipeline = new VoiceRecordingPipeline({
+ stream,
+ segmentMs: 1000,
+ onSegment: vi.fn(),
+ onStopped,
+ });
+ await pipeline.start();
+
+ expect(FakeAudioContext.instance).not.toBeNull();
+ expect(addModule).toHaveBeenCalledOnce();
+ expect(FakeAudioContext.instance?.createMediaStreamSource).toHaveBeenCalledOnce();
+
+ pipeline.abort();
+ FakeAudioWorkletNode.instance?.port.onmessage?.({ data: { type: 'stopped' } });
+ expect(onStopped).toHaveBeenCalledWith('abort', { pendingSegmentCount: 0 });
+ // The real worklet acknowledges stop through its message port. The test
+ // drives that boundary so the shared context can be closed cleanly.
+ await FakeAudioContext.instance?.close();
+ });
+
it('observes a microphone track ending while the worklet module loads', async () => {
let resolveModule!: () => void;
const addModule = vi.fn(() => new Promise<void>((resolve) => {
diff --git a/ui/src/lib/voiceRecording.ts b/ui/src/lib/voiceRecording.ts
index 653142955..26f275ea2 100644
--- a/ui/src/lib/voiceRecording.ts
+++ b/ui/src/lib/voiceRecording.ts
@@ -143,6 +143,120 @@ registerProcessor('${PCM_WORKLET_NAME}', AvibeVoicePcmCapture);
export const voicePcmWorkletSource = PCM_WORKLET_SOURCE;
+type AudioContextConstructor = new () => AudioContext;
+
+let prewarmedAudioContext: AudioContext | null = null;
+let prewarmedAudioContextConstructor: AudioContextConstructor | null = null;
+let prewarmPromise: Promise<void> | null = null;
+
+const audioContextConstructor = (): AudioContextConstructor | null => {
+ const constructor = globalThis.AudioContext;
+ return typeof constructor === 'function' ? constructor : null;
+};
+
+const clearPrewarmedAudioContext = (context: AudioContext): void => {
+ if (prewarmedAudioContext !== context) return;
+ prewarmedAudioContext = null;
+ prewarmedAudioContextConstructor = null;
+ prewarmPromise = null;
+};
+
+const closePrewarmedAudioContext = (context: AudioContext): void => {
+ clearPrewarmedAudioContext(context);
+ if (context.state !== 'closed') void context.close().catch(() => undefined);
+};
+
+const loadVoicePcmWorklet = async (context: AudioContext): Promise<void> => {
+ const moduleUrl = URL.createObjectURL(
+ new Blob([PCM_WORKLET_SOURCE], { type: 'text/javascript' }),
+ );
+ try {
+ await context.audioWorklet.addModule(moduleUrl);
+ } finally {
+ URL.revokeObjectURL(moduleUrl);
+ }
+};
+
+const requestAudioContextResume = (context: AudioContext): void => {
+ if (context.state === 'running') return;
+ try {
+ // Invoke resume synchronously from the microphone pointer/shortcut handler.
+ // The promise may settle later, but the browser's transient activation is
+ // attached to this call itself.
+ void context.resume().catch(() => undefined);
+ } catch {
+ // start() retries resume after the worklet and stream are connected.
+ }
+};
+
+/**
+ * Compile the capture worklet before the user presses the microphone button.
+ * This does not request microphone permission or connect a MediaStream; it only
+ * keeps the audio graph ready so the first spoken words do not race worklet
+ * compilation and AudioContext startup.
+ */
+export const prewarmVoiceCapture = (): Promise<void> => {
+ const constructor = audioContextConstructor();
+ if (!constructor) return Promise.resolve();
+
+ if (
+ prewarmedAudioContext
+ && (
+ prewarmedAudioContextConstructor !== constructor
+ || prewarmedAudioContext.state === 'closed'
+ )
+ ) {
+ closePrewarmedAudioContext(prewarmedAudioContext);
+ }
+ if (prewarmPromise) {
+ if (prewarmedAudioContext) requestAudioContextResume(prewarmedAudioContext);
+ return prewarmPromise;
+ }
+
+ let context: AudioContext;
+ try {
+ context = new constructor();
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ prewarmedAudioContext = context;
+ prewarmedAudioContextConstructor = constructor;
+ requestAudioContextResume(context);
+ prewarmPromise = (async () => {
+ try {
+ await loadVoicePcmWorklet(context);
+ } catch (error) {
+ closePrewarmedAudioContext(context);
+ throw error;
+ }
+ })();
+ return prewarmPromise;
+};
+
+const acquireAudioContext = async (): Promise<{
+ context: AudioContext;
+ prewarmed: boolean;
+}> => {
+ const constructor = audioContextConstructor();
+ if (!constructor) throw new Error('AudioContext unavailable');
+
+ if (
+ prewarmedAudioContext
+ && prewarmedAudioContextConstructor !== constructor
+ ) {
+ closePrewarmedAudioContext(prewarmedAudioContext);
+ }
+ if (prewarmPromise) await prewarmPromise.catch(() => undefined);
+ if (
+ prewarmedAudioContext
+ && prewarmedAudioContextConstructor === constructor
+ && prewarmedAudioContext.state !== 'closed'
+ ) {
+ return { context: prewarmedAudioContext, prewarmed: true };
+ }
+ return { context: new constructor(), prewarmed: false };
+};
+
type VoicePcmCaptureHandlers = {
onSamples: (samples: Int16Array<ArrayBuffer>) => void;
onStopped: () => void;
@@ -169,6 +283,7 @@ class AudioWorkletPcmCapture implements VoicePcmCapture {
private readonly handlers: VoicePcmCaptureHandlers;
private readonly stopTimeoutMs: number;
private context: AudioContext | null = null;
+ private sharedContext = false;
private source: MediaStreamAudioSourceNode | null = null;
private node: AudioWorkletNode | null = null;
private stopTimer: ReturnType<typeof setTimeout> | null = null;
@@ -191,63 +306,75 @@ class AudioWorkletPcmCapture implements VoicePcmCapture {
}
async start(): Promise<void> {
- const context = new AudioContext();
- this.context = context;
- this.stream.getTracks().forEach((track) => {
- track.addEventListener('ended', this.handleTrackEnded, { once: true });
- });
- if (this.stream.getTracks().some((track) => track.readyState === 'ended')) {
- this.stop();
- }
- let moduleUrl: string | null = null;
+ let context: AudioContext | null = null;
try {
- moduleUrl = URL.createObjectURL(
- new Blob([PCM_WORKLET_SOURCE], { type: 'text/javascript' }),
- );
- await context.audioWorklet.addModule(moduleUrl);
- if (this.stopping) {
- await context.close();
- this.finish();
- return;
- }
-
- const node = new AudioWorkletNode(context, PCM_WORKLET_NAME, {
- numberOfInputs: 1,
- numberOfOutputs: 1,
- outputChannelCount: [1],
- processorOptions: {
- targetSampleRate: this.sampleRate,
- // File-sized segments are assembled on the main thread. Deliver
- // smaller chunks so a processor failure cannot erase a whole segment.
- chunkSamples: voicePcmDeliverySamples(this.sampleRate, this.segmentSamples),
- },
+ const acquired = await acquireAudioContext();
+ context = acquired.context;
+ this.context = context;
+ this.sharedContext = acquired.prewarmed;
+ this.stream.getTracks().forEach((track) => {
+ track.addEventListener('ended', this.handleTrackEnded, { once: true });
});
- node.port.onmessage = (event: MessageEvent<{
- type?: string;
- samples?: ArrayBuffer;
- }>) => {
- if (event.data.type === 'samples' && event.data.samples) {
- this.handlers.onSamples(new Int16Array(event.data.samples));
- } else if (event.data.type === 'stopped') {
+ if (this.stream.getTracks().some((track) => track.readyState === 'ended')) {
+ this.stop();
+ }
+ let moduleUrl: string | null = null;
+ try {
+ if (!acquired.prewarmed) {
+ moduleUrl = URL.createObjectURL(
+ new Blob([PCM_WORKLET_SOURCE], { type: 'text/javascript' }),
+ );
+ await context.audioWorklet.addModule(moduleUrl);
+ }
+ if (this.stopping) {
this.finish();
+ return;
}
- };
- node.onprocessorerror = () => {
- this.reportFailure(new Error('voice PCM processor stopped unexpectedly'));
- this.finish();
- };
- this.node = node;
- this.source = context.createMediaStreamSource(this.stream);
- this.source.connect(node);
- node.connect(context.destination);
- await context.resume();
+
+ const node = new AudioWorkletNode(context, PCM_WORKLET_NAME, {
+ numberOfInputs: 1,
+ numberOfOutputs: 1,
+ outputChannelCount: [1],
+ processorOptions: {
+ targetSampleRate: this.sampleRate,
+ // File-sized segments are assembled on the main thread. Deliver
+ // smaller chunks so a processor failure cannot erase a whole segment.
+ chunkSamples: voicePcmDeliverySamples(this.sampleRate, this.segmentSamples),
+ },
+ });
+ node.port.onmessage = (event: MessageEvent<{
+ type?: string;
+ samples?: ArrayBuffer;
+ }>) => {
+ if (event.data.type === 'samples' && event.data.samples) {
+ this.handlers.onSamples(new Int16Array(event.data.samples));
+ } else if (event.data.type === 'stopped') {
+ this.finish();
+ }
+ };
+ node.onprocessorerror = () => {
+ this.reportFailure(new Error('voice PCM processor stopped unexpectedly'));
+ this.finish();
+ };
+ this.node = node;
+ this.source = context.createMediaStreamSource(this.stream);
+ this.source.connect(node);
+ node.connect(context.destination);
+ await context.resume();
+ } finally {
+ if (moduleUrl) URL.revokeObjectURL(moduleUrl);
+ }
} catch (error) {
this.detachNodes();
this.context = null;
- if (context.state !== 'closed') await context.close().catch(() => undefined);
+ const failedContext = context;
+ const sharedContext = this.sharedContext;
+ this.sharedContext = false;
+ if (failedContext) {
+ if (sharedContext) closePrewarmedAudioContext(failedContext);
+ else if (failedContext.state !== 'closed') await failedContext.close().catch(() => undefined);
+ }
throw error;
- } finally {
- if (moduleUrl) URL.revokeObjectURL(moduleUrl);
}
}
@@ -282,8 +409,12 @@ class AudioWorkletPcmCapture implements VoicePcmCapture {
this.stopTimer = null;
this.detachNodes();
const context = this.context;
+ const sharedContext = this.sharedContext;
this.context = null;
- if (context && context.state !== 'closed') void context.close().catch(() => undefined);
+ this.sharedContext = false;
+ if (context && !sharedContext && context.state !== 'closed') {
+ void context.close().catch(() => undefined);
+ }
this.handlers.onStopped();
}