Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.
JavaScript agent-collaborationagent-harnessagent-orchestrationagent-teamagent-workflowai-assistantai-automationai-employeeai-productivityai-teamai-workflowautonomous-agentsclaude-code-guiclaude-coworkdesktop-agentlocal-firstmulti-agentmulti-agent-systemself-evolving-agentstask-automation
Wait for voice service and capture readiness before recording
wyt86635fd0db70
diff --git a/src/renderer/modules/voice-input.js b/src/renderer/modules/voice-input.jsindex 11b84d07..5f8f325d 100644--- a/src/renderer/modules/voice-input.js+++ b/src/renderer/modules/voice-input.js@@ -32,6 +32,28 @@return { code: publicCode || _voiceErrorCode(e && (e.name || e.message)) };}+ function voiceNow() {+ return typeof performance !== 'undefined' ? performance.now() : Date.now();+ }++ function markVoiceTiming(attempt, stage) {+ if (!attempt || attempt.timingReported || attempt.timings[stage] !== undefined) return;+ attempt.timings[stage] = Math.max(0, Math.round(voiceNow() - attempt.timingStart));+ }++ function reportVoiceTiming(attempt) {+ if (!attempt || attempt.timingReported) return;+ markVoiceTiming(attempt, 'total_ms');+ attempt.timingReported = true;+ const timings = attempt.timings;+ const finalWait = timings.stop_ms !== undefined && timings.final_text_ms !== undefined+ ? Math.max(0, timings.final_text_ms - timings.stop_ms) : undefined;+ // One local summary per attempt, numeric milestones only. Never retain audio,+ // transcript text, credentials, or the session-bearing WebSocket URL.+ try { voiceLog?.info('voice timing', { ...timings, final_wait_ms: finalWait,+ phase: attempt.phase, terminal: timings.final_text_ms !== undefined }); } catch {}+ }+async function gzipBytes(u8) {const stream = new Blob([u8]).stream().pipeThrough(new CompressionStream('gzip'));return new Uint8Array(await new Response(stream).arrayBuffer());@@ -114,6 +136,7 @@return;}this._mediaStream = mediaStream;+ this._emit('onStage', 'microphone_ms');let ws;try {ws = new WebSocket(this._connectUrl());@@ -149,10 +172,9 @@return;}try { if (voiceLog) voiceLog.info('ASR websocket open'); } catch {}- clearTimeout(this._connectTimer);- this._running = true;- this._emit('onOpen');- this._startCapture();+ this._emit('onStage', 'socket_open_ms');+ // The ticket protocol sends ready only after auth, quota and provider setup.+ // Keep the setup deadline active until capture is actually ready.};ws.onmessage = (ev) => {if (this._ws !== ws) return;@@ -203,8 +225,14 @@_handleJSON(s) {let obj;try { obj = JSON.parse(String(s || '{}')); } catch { return; }- // Some public peers send a ready control message; it is not a transcript.- if (obj && obj.event === 'ready') return;+ if (obj && obj.event === 'ready') {+ if (!this._running && !this._pendingClose && this._ws?.readyState === WebSocket.OPEN) {+ this._emit('onStage', 'service_ready_ms');+ this._running = true;+ this._startCapture();+ }+ return;+ }if (obj && obj.event === 'timeout') {const err = Object.assign(new Error('asr_timeout'), { code: 'timeout' });err.maxSeconds = Number(obj.max_seconds || obj.maxSeconds || 0) || undefined;@@ -310,7 +338,8 @@if (!ms) throw new Error('no_media_stream');const Ctx = window.AudioContext || window.webkitAudioContext;this._audioCtx = new Ctx();- try { if (this._audioCtx.state === 'suspended') await this._audioCtx.resume(); } catch {}+ if (this._audioCtx.state === 'suspended') await this._audioCtx.resume();+ if (active() && this._audioCtx.state !== 'running') throw new Error('audio_context_unavailable');if (!active()) return;this._source = this._audioCtx.createMediaStreamSource(ms);this._inRate = this._audioCtx.sampleRate || 48000;@@ -418,6 +447,8 @@ registerProcessor('orkas-asr-capture', C);`;try { this._silentGain.gain.value = 0; } catch {}this._captureNode.connect(this._silentGain);this._silentGain.connect(this._audioCtx.destination);+ clearTimeout(this._connectTimer);+ this._emit('onOpen');} catch (e) {if (!active()) return;try { if (voiceLog) voiceLog.error('audio capture start failed', _errorInfo(e)); } catch {}@@ -673,11 +704,11 @@ registerProcessor('orkas-asr-capture', C);`;function setPhase(p) {phase = p;buttonEl.dataset.voicePhase = p;- buttonEl.classList.toggle('is-recording', p === 'recording' || p === 'connecting');- buttonEl.classList.toggle('is-busy', p === 'finalizing');- const titleKey = p === 'finalizing' ? 'chat.mic_finalizing' : (p === 'recording' || p === 'connecting')+ buttonEl.classList.toggle('is-recording', p === 'recording');+ buttonEl.classList.toggle('is-busy', p === 'connecting' || p === 'finalizing');+ const titleKey = p === 'connecting' ? 'chat.mic_connecting' : p === 'finalizing' ? 'chat.mic_finalizing' : (p === 'recording' || p === 'connecting')? 'chat.mic_stop_title' : 'chat.mic_title';- const titleFallback = p === 'finalizing' ? 'Finishing recognition…' : (p === 'recording' || p === 'connecting')+ const titleFallback = p === 'connecting' ? 'Connecting…' : p === 'finalizing' ? 'Finishing recognition…' : (p === 'recording' || p === 'connecting')? 'Stop recording' : 'Voice input';buttonEl.title = _t(titleKey, titleFallback);buttonEl.setAttribute('aria-label', buttonEl.title);@@ -702,6 +733,7 @@ registerProcessor('orkas-asr-capture', C);`;}function reset(attempt) {+ reportVoiceTiming(attempt);clearLimitTimer(attempt);attempt.insertion?.dispose();if (activeAttempt !== attempt) return;@@ -739,6 +771,7 @@ registerProcessor('orkas-asr-capture', C);`;if (activeAttempt) return;if (cancelActive) cancelActive();const attempt = {+ timingStart: voiceNow(), timings: {}, timingReported: false,recordingStarted: false,finished: false,cancelled: false,@@ -789,6 +822,7 @@ registerProcessor('orkas-asr-capture', C);`;}if (!r || r.ok === false || !r.url) throw new Error((r && r.error) || 'no_url');url = r.url;+ markVoiceTiming(attempt, 'session_ms');} catch (e) {if (activeAttempt !== attempt || attempt.cancelled) return;try { if (voiceLog) voiceLog.error('failed to resolve ASR websocket URL', _errorInfo(e)); } catch {}@@ -800,14 +834,18 @@ registerProcessor('orkas-asr-capture', C);`;if (activeAttempt !== attempt || attempt.cancelled) return;if (!attempt.insertion?.valid()) { reset(attempt); return; }const attemptClient = new AsrClient(url, {+ onStage: (stage) => { if (activeAttempt === attempt) markVoiceTiming(attempt, stage); },onOpen: () => {if (activeAttempt !== attempt) return;+ markVoiceTiming(attempt, 'capture_ready_ms');attempt.recordingStarted = true;setAttemptPhase(attempt, 'recording');startLimitTimer(attempt);},onResult: ({ text, last }) => {if (activeAttempt !== attempt) return;+ if (text) markVoiceTiming(attempt, 'first_text_ms');+ if (last) markVoiceTiming(attempt, 'final_text_ms');if (text) applyTranscript(attempt, text);if (last && activeAttempt === attempt) {attempt.finished = true; reset(attempt); attemptClient.close();@@ -881,9 +919,10 @@ registerProcessor('orkas-asr-capture', C);`;const attemptClient = attempt.client;attempt.finished = true;reset(attempt);- try { if (attemptClient) attemptClient.stop(); } catch {}+ try { if (attemptClient) attemptClient.close(); } catch {}return;}+ markVoiceTiming(attempt, 'stop_ms');setAttemptPhase(attempt, 'finalizing');try {if (!attempt.client) throw new Error('voice_client_unavailable');diff --git a/test/e2e/fixtures/orkas.ts b/test/e2e/fixtures/orkas.tsindex 900698fe..6826e5e4 100644--- a/test/e2e/fixtures/orkas.ts+++ b/test/e2e/fixtures/orkas.ts@@ -3632,6 +3632,8 @@ export class OrkasTestApp {'','',].join('\r\n'));+ const ready = Buffer.from('{"event":"ready"}');+ socket.write(Buffer.concat([Buffer.from([0x81, ready.length]), ready]));};// Keep the HTTP upgrade pending until the client cancels. This makes// the negotiation-cancellation contract deterministic under load;diff --git a/test/e2e/voice_input_e2e_lifecycle.spec.ts b/test/e2e/voice_input_e2e_lifecycle.spec.tsindex 117e2b9a..310ede9a 100644--- a/test/e2e/voice_input_e2e_lifecycle.spec.ts+++ b/test/e2e/voice_input_e2e_lifecycle.spec.ts@@ -88,7 +88,8 @@ test.describe('voice input', () => {const mic = page.locator('#new-chat-mic-btn');await input.fill('Keep this draft');await mic.click();- await expect(mic).toHaveClass(/\bis-recording\b/);+ await expect(mic).toHaveClass(/\bis-busy\b/);+ await expect(mic).not.toHaveClass(/\bis-recording\b/);await expect.poll(() => page.evaluate(() => (window as any).__e2eVoiceSocketUrls.length)).toBe(1);await mic.click();@@ -152,9 +153,11 @@ test.describe('API-key voice input', () => {await (window as any).orkas.invoke('orkasApi.save', { apiKey: 'synthetic-voice-e2e-key' });const w = window as any;w.__voiceStops = 0;+ w.__voiceCaptures = 0;Object.defineProperty(navigator.mediaDevices, 'getUserMedia', { configurable: true, value: async () => ({ getTracks: () => [{ stop() { w.__voiceStops++; } }] }) });const node = () => ({ connect() {}, disconnect() {} });w.AudioContext = class {+ constructor() { w.__voiceCaptures++; }state = 'running'; sampleRate = 48000; destination = {};audioWorklet = { addModule: async () => {} };createMediaStreamSource = node;@@ -180,7 +183,8 @@ test.describe('API-key voice input', () => {const accept = createHash('sha1').update(key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').digest('base64');const upgrade = () => socket.write('HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ' + accept + '\r\n\r\n');const ready = Buffer.from('{"event":"ready"}');- sendReady = () => { upgrade(); socket.write(Buffer.concat([Buffer.from([0x81, ready.length]), ready])); };+ upgrade();+ sendReady = () => { socket.write(Buffer.concat([Buffer.from([0x81, ready.length]), ready])); };let buffer = Buffer.alloc(0);socket.on('data', chunk => {buffer = Buffer.concat([buffer, chunk]);@@ -206,6 +210,7 @@ test.describe('API-key voice input', () => {constructor(url: string, protocols?: string | string[]) {if (!url.startsWith('wss://orkas.ai/api/voice/asr_ws?ticket=')) throw new Error('Unexpected voice destination');super('ws://127.0.0.1:' + port + '/api/voice/asr_ws', protocols);+ this.addEventListener('open', () => { (window as any).__voiceTransportOpen = true; });}};}, (server.address() as AddressInfo).port);@@ -221,13 +226,19 @@ test.describe('API-key voice input', () => {await expect(page.locator('.chat-mic-status:visible')).toHaveCount(0);};await expect(mic).toHaveAttribute('data-voice-phase', 'connecting');- await expectActiveIcon();+ await expect.poll(() => page.evaluate(() => !!(window as any).__voiceTransportOpen)).toBe(true);+ await expect(mic).toHaveClass(/is-busy/);+ await expect(mic).not.toHaveClass(/is-recording/);+ await expect(mic).toHaveCSS('animation-name', 'none');+ await expect(mic).toHaveAttribute('aria-label', 'Connecting…');+ expect(await page.evaluate(() => (window as any).__voiceCaptures)).toBe(0);await page.screenshot({ path: testInfo.outputPath('voice-connecting-en.png') });await expect.poll(() => !!sendReady).toBe(true);await expect(page.locator('.ui-dialog-overlay.open')).toHaveCount(0);sendReady!();await expect(mic).toHaveAttribute('data-voice-phase', 'recording');await expectActiveIcon();+ expect(await page.evaluate(() => (window as any).__voiceCaptures)).toBe(1);await page.screenshot({ path: testInfo.outputPath('voice-recording-en.png') });await page.setViewportSize({ width: 760, height: 600 });await page.evaluate(async () => { await (window as any).setLang('zh'); });diff --git a/test/renderer/voice-input.test.ts b/test/renderer/voice-input.test.tsindex 0b551381..e1b41ba1 100644--- a/test/renderer/voice-input.test.ts+++ b/test/renderer/voice-input.test.ts@@ -136,9 +136,11 @@ function loadCompressedCapture(sourcePath: string, failCompression = false) {readyState = Socket.CONNECTING;frames: (Buffer | string)[] = [];onopen?: () => void;+ onmessage?: (event: any) => void;onclose?: () => void;constructor(readonly url: string) { sockets.push(this); }- open() { this.readyState = Socket.OPEN; this.onopen?.(); }+ open(ready = true) { this.readyState = Socket.OPEN; this.onopen?.(); if (ready) this.ready(); }+ ready() { this.onmessage?.({ data: '{"event":"ready"}' }); }send(value: Uint8Array | string) {if (this.readyState !== Socket.OPEN) throw new Error('socket is closed');this.frames.push(typeof value === 'string' ? value : Buffer.from(value));@@ -168,6 +170,7 @@ function loadWorkletCapture(sourcePath: string, options: {delayedModule?: boolean;delayedPermission?: boolean;dropFlush?: boolean;+ resumeFails?: boolean;} = {}) {const modules = new Map<string, string>();let releaseModule: () => void = () => {};@@ -213,7 +216,8 @@ function loadWorkletCapture(sourcePath: string, options: {disconnect() {}}class CaptureContext {- state = 'running';+ state = options.resumeFails ? 'suspended' : 'running';+ resume() { return Promise.reject(new Error('audio_resume_failed')); }sampleRate = 16_000;destination = {};audioWorklet = {@@ -249,9 +253,11 @@ function loadWorkletCapture(sourcePath: string, options: {readyState = Socket.CONNECTING;frames: (Buffer | string)[] = [];onopen?: () => void;+ onmessage?: (event: any) => void;onclose?: () => void;constructor(_url: string) { sockets.push(this); }- open() { this.readyState = Socket.OPEN; this.onopen?.(); }+ open(ready = true) { this.readyState = Socket.OPEN; this.onopen?.(); if (ready) this.ready(); }+ ready() { this.onmessage?.({ data: '{"event":"ready"}' }); }send(value: Uint8Array | string) {this.frames.push(typeof value === 'string' ? value : Buffer.from(value));}@@ -271,7 +277,9 @@ function loadWorkletCapture(sourcePath: string, options: {};context.clearTimeout = (id: number) => timers.delete(id);const errors: Error[] = [];+ const opened: boolean[] = [];const client = context.window.VoiceInput.createClient('wss://example.test/asr', {+ onOpen: () => opened.push(true),onError: (error: Error) => errors.push(error),});const processSamples = (count: number) => {@@ -283,7 +291,7 @@ function loadWorkletCapture(sourcePath: string, options: {}};return {- client, nodes, sockets, errors, timers, processSamples, releaseModule,+ client, nodes, sockets, errors, opened, timers, processSamples, releaseModule,grantPermission: () => grantPermission(stream),tracksStopped: () => tracksStopped,};@@ -330,7 +338,8 @@ function loadDelayedTranscript(sourcePath: string) {onmessage?: (event: any) => void;onclose?: (event: any) => void;constructor(_url: string) { sockets.push(this); }- open() { this.readyState = Socket.OPEN; this.onopen?.(); }+ open(ready = true) { this.readyState = Socket.OPEN; this.onopen?.(); if (ready) this.ready(); }+ ready() { this.onmessage?.({ data: '{"event":"ready"}' }); }receive(text: string, terminal = false) {const payload = gzipSync(Buffer.from(JSON.stringify({ result: { text } })));const frame = Buffer.alloc(12 + payload.length);@@ -454,6 +463,30 @@ describe.each([fixture.client.close();});+ it('never announces recording if the audio device cannot resume', async () => {+ const fixture = loadWorkletCapture(sourcePath, { resumeFails: true });+ await fixture.client.start(); fixture.sockets[0].open();+ await new Promise<void>(resolve => setImmediate(resolve));+ expect(fixture.opened).toEqual([]);+ expect(fixture.nodes).toEqual([]);+ expect(fixture.errors.map(error => error.message)).toEqual(['audio_resume_failed']);+ fixture.client.close();+ expect(fixture.tracksStopped()).toBe(1);+ });++ it('announces recording only after the capture graph is ready', async () => {+ const fixture = loadWorkletCapture(sourcePath, { delayedModule: true });+ await fixture.client.start(); fixture.sockets[0].open();+ await new Promise<void>(resolve => setImmediate(resolve));+ expect(fixture.opened).toEqual([]);+ expect(fixture.nodes).toEqual([]);+ fixture.releaseModule();+ await new Promise<void>(resolve => setImmediate(resolve));+ expect(fixture.opened).toEqual([true]);+ expect(fixture.nodes).toHaveLength(1);+ fixture.client.close();+ });+it('does not create capture resources after a pending worklet load is stopped', async () => {const fixture = loadWorkletCapture(sourcePath, { delayedModule: true });await fixture.client.start();@@ -709,7 +742,8 @@ function controllerHarness(voiceOverrides: Record<string, unknown> = {}, globalssend = vi.fn();close = vi.fn(() => { this.readyState = Socket.CLOSED; this.onclose?.({code:1000}); });constructor(readonly url: string) { sockets.push(this); }- open() { this.readyState = Socket.OPEN; this.onopen?.(); }+ open(ready = true) { this.readyState = Socket.OPEN; this.onopen?.(); if (ready) this.ready(); }+ ready() { this.onmessage?.({ data: '{"event":"ready"}' }); }result(text: string, last = false) { this.onmessage?.({data:JSON.stringify({result:{text,last}})}); }error(reason: string) { this.onmessage?.({data:JSON.stringify({event:'error',reason})}); }}@@ -905,6 +939,65 @@ describe('voice input controller ticket and composer ownership', () => {// Remote UI/permission guidance uses the existing controller, preserving all// wire-order and composer-owner regression cases above.describe('public voice recording controls', () => {+ it('records one bounded timing summary without retaining the key, audio or recognized text', async () => {+ let now = 0;+ const records: any[] = [];+ const h = controllerHarness({}, { performance: { now: () => now },+ createLogger: () => ({ info: (...args: any[]) => records.push(args), warn() {}, error() {} }) });+ await h.start(); now = 300; h.sockets[0].open(false);+ now = 900; h.sockets[0].ready(); await h.settle();+ now = 1400; h.sockets[0].result('private spoken text');+ now = 2000; h.button.click();+ now = 2400; h.sockets[0].result('private spoken text', true); await h.settle();+ const summaries = records.filter(record => record[0] === 'voice timing');+ expect(summaries).toHaveLength(1);+ expect(summaries[0][1]).toMatchObject({ socket_open_ms: 300, service_ready_ms: 900,+ capture_ready_ms: 900, first_text_ms: 1400, stop_ms: 2000, final_text_ms: 2400,+ final_wait_ms: 400, total_ms: 2400 });+ expect(JSON.stringify(records)).not.toMatch(/private spoken text|one-use|example.test/);+ });++ it('waits for service readiness before recording, and a duplicate ready cannot recreate capture', async () => {+ const h = controllerHarness();+ await h.start();+ const socket = h.sockets[0]; socket.open(false);+ expect(h.button.classList.contains('is-recording')).toBe(false);+ expect(h.button.dataset.voicePhase).toBe('connecting');+ expect(h.captureNodes).toHaveLength(0);+ expect(socket.send).not.toHaveBeenCalled();+ socket.ready(); await h.settle();+ expect(h.button.dataset.voicePhase).toBe('recording');+ expect(h.captureNodes).toHaveLength(1);+ socket.ready(); await h.settle();+ expect(h.captureNodes).toHaveLength(1);+ h.ownerChange();+ });+ it('cancels while waiting for ready without capturing late audio or altering the draft', async () => {+ const h = controllerHarness(); await h.start();+ const socket = h.sockets[0]; socket.open(false);+ h.button.click(); socket.ready(); await h.settle();+ expect(h.captureNodes).toHaveLength(0);+ expect(socket.send).not.toHaveBeenCalled();+ expect(socket.close).toHaveBeenCalledTimes(1);+ expect(h.stopped).toHaveBeenCalledTimes(1);+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.textarea.value).toBe('Keep this draft');+ expect(h.alerts).toEqual([]);+ expect(h.timers.size).toBe(0);+ });+ it('bounds a missing ready event and lets the user retry with the draft intact', async () => {+ const h = controllerHarness(); await h.start();+ const socket = h.sockets[0]; socket.open(false);+ expect(h.timers.size).toBe(1);+ [...h.timers.values()][0](); await h.settle();+ expect(h.captureNodes).toHaveLength(0);+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.textarea.value).toBe('Keep this draft');+ expect(h.alerts).toEqual([h.context.t('chat.mic_error_unavailable')]);+ await h.start(); h.sockets[1].open();+ expect(h.button.dataset.voicePhase).toBe('recording');+ h.ownerChange();+ });it('starts without an introduction and keeps icon-only state across repeat attempts', async () => {const h = controllerHarness();const state = (phase: string, recording: boolean, busy: boolean) => {@@ -915,7 +1008,7 @@ describe('public voice recording controls', () => {};state('idle', false, false);for (let n = 0; n < 2; n++) {- await h.start(); state('connecting', true, false);+ await h.start(); state('connecting', false, true);const socket = h.sockets[n]; socket.open(); state('recording', true, false);h.button.click(); state('finalizing', false, true);expect(h.button.title).toBe(h.context.t('chat.mic_finalizing'));