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
Preserve API-key voice input and editor transactions
wytf3df205d0af5
diff --git a/src/main/features/voice_input.ts b/src/main/features/voice_input.tsnew file mode 100644index 00000000..7a37fd9c--- /dev/null+++ b/src/main/features/voice_input.ts@@ -0,0 +1,46 @@+import { systemPreferences } from 'electron';+import { getOrkasApiKey } from './auth';+import { getActiveUserId } from './users';+import { ORKAS_API_BASE_URL } from './orkas_api';+import { fetchAndReadWithTimeout } from '../util/abort';++type VoiceSession = { ok: true; url: string; maxSeconds: number }+ | { ok: false; error: 'E_ORKAS_API_KEY_REQUIRED' | 'E_VOICE_UNAVAILABLE' };++/** The long-lived credential never crosses IPC; only a one-use ticket does. */+export async function createVoiceSession(): Promise<VoiceSession> {+ const key = getOrkasApiKey();+ if (!key) return { ok: false, error: 'E_ORKAS_API_KEY_REQUIRED' };+ const owner = getActiveUserId();+ try {+ const { response, body } = await fetchAndReadWithTimeout<unknown>(+ ORKAS_API_BASE_URL + '/audio/transcription_sessions',+ { method: 'POST', redirect: 'error', headers: {+ Authorization: `Bearer ${key}`, 'Content-Type': 'application/json',+ }, body: '{}' },+ 60_000, undefined, 'voice session unavailable',+ async (reply) => reply.ok ? reply.json() : null,+ );+ if (owner !== getActiveUserId() || key !== getOrkasApiKey()) {+ return { ok: false, error: 'E_VOICE_UNAVAILABLE' };+ }+ if (response.status === 401 || response.status === 403) {+ return { ok: false, error: 'E_ORKAS_API_KEY_REQUIRED' };+ }+ const ticket = body && typeof body === 'object' && 'ticket' in body ? body.ticket : null;+ if (!response.ok || typeof ticket !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(ticket)) {+ return { ok: false, error: 'E_VOICE_UNAVAILABLE' };+ }+ return { ok: true, url: 'wss://orkas.ai/api/voice/asr_ws?ticket=' + ticket, maxSeconds: 120 };+ } catch {+ return { ok: false, error: 'E_VOICE_UNAVAILABLE' };+ }+}++export async function ensureMicrophoneAccess(): Promise<{ granted: boolean; status: string }> {+ if (process.platform !== 'darwin') return { granted: true, status: 'granted' };+ const status = systemPreferences.getMediaAccessStatus('microphone');+ if (status !== 'not-determined') return { granted: status === 'granted', status };+ const granted = await systemPreferences.askForMediaAccess('microphone');+ return { granted, status: granted ? 'granted' : systemPreferences.getMediaAccessStatus('microphone') };+}diff --git a/src/renderer/modules/voice-input.js b/src/renderer/modules/voice-input.jsnew file mode 100644index 00000000..b39dff0b--- /dev/null+++ b/src/renderer/modules/voice-input.js@@ -0,0 +1,795 @@+// Voice-to-text for the chat composers.+//+// Adds a microphone button next to the "+" attach button in the new-chat+// landing composer and the conversation composer. Clicking it captures the+// mic (getUserMedia + an AudioWorklet that downsamples to 16 kHz / 16-bit+// PCM), streams the PCM (gzip-compressed when the browser supports it) over+// a WebSocket to the Server's `/voice/asr_ws` proxy (a thin front for+// VolcEngine's streaming ASR), and writes the recognised text into the+// textarea live. Clicking again stops; the final text stays in the box and+// is NOT auto-sent — the user reviews and presses send themselves.+//+// The user-owned API key stays in main; the renderer receives a one-use ticket.+//+// Classic script — no import/export; exposes the global `VoiceInput`.++(function () {+ 'use strict';++ const HAS_GZIP =+ typeof CompressionStream === 'function' && typeof DecompressionStream === 'function';+ const VOICE_MAX_DURATION_MS = 120 * 1000;+ const voiceLog = (() => {+ try { return typeof createLogger === 'function' ? createLogger('voice-input') : null; } catch { return null; }+ })();++ function _errorInfo(e) {+ return { code: _voiceErrorCode(e && (e.name || e.message)) };+ }++ async function gzipBytes(u8) {+ const stream = new Blob([u8]).stream().pipeThrough(new CompressionStream('gzip'));+ return new Uint8Array(await new Response(stream).arrayBuffer());+ }++ async function gunzipBytes(u8) {+ const stream = new Blob([u8]).stream().pipeThrough(new DecompressionStream('gzip'));+ return new Uint8Array(await new Response(stream).arrayBuffer());+ }++ // ── Low-level streaming-ASR client (VolcEngine binary protocol). ──────────+ // Ported from the AIBase web client; the wire framing matches the Server+ // proxy's `biz/voice/asr.py`.+ class AsrClient {+ constructor(wsUrl, callbacks) {+ this._url = wsUrl;+ this._cb = callbacks || {};+ this._ws = null;+ this._running = false;+ this._pendingClose = false;+ this._cancelledBeforeOpen = false;+ this._lastText = '';+ this._audioCtx = null;+ this._mediaStream = null;+ this._source = null;+ this._workletNode = null;+ this._scriptNode = null;+ this._captureNode = null;+ this._workletModuleURL = null;+ this._silentGain = null;+ this._inRate = 0;+ this._chunkMs = 200;+ this._chunkFrames = 0;+ this._useGzip = HAS_GZIP;+ this._closeEmitted = false;+ this._sendTail = Promise.resolve();+ this._inputEnded = false;+ this._captureEpoch = 0;+ this._captureFlush = null;+ }++ _emit(name, ...args) {+ const fn = this._cb[name];+ if (typeof fn === 'function') {+ try { fn(...args); } catch (e) { /* renderer callback threw */ }+ }+ }++ _connectUrl() {+ try {+ const u = new URL(this._url);+ u.searchParams.set('encoding', this._useGzip ? 'gzip' : 'raw');+ return u.toString();+ } catch {+ return this._url + (this._url.includes('?') ? '&' : '?') + 'encoding=' + (this._useGzip ? 'gzip' : 'raw');+ }+ }++ async start() {+ if (this._ws && (this._ws.readyState === WebSocket.OPEN || this._ws.readyState === WebSocket.CONNECTING)) return;+ const epoch = ++this._captureEpoch;+ this._closeEmitted = false;+ // Acquire the mic FIRST so a permission denial fails before we open the+ // socket (cleaner than tearing down a live WS in the error path).+ let mediaStream;+ try {+ mediaStream = await navigator.mediaDevices.getUserMedia({+ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true },+ });+ } catch (e) {+ if (epoch !== this._captureEpoch) return;+ try { if (voiceLog) voiceLog.error('getUserMedia failed', _errorInfo(e)); } catch {}+ this._emit('onError', e);+ return;+ }+ if (epoch !== this._captureEpoch || this._pendingClose) {+ try { mediaStream.getTracks().forEach((tr) => { try { tr.stop(); } catch {} }); } catch {}+ return;+ }+ this._mediaStream = mediaStream;+ let ws;+ try {+ ws = new WebSocket(this._connectUrl());+ } catch (e) {+ try { if (voiceLog) voiceLog.error('ASR websocket constructor failed', _errorInfo(e)); } catch {}+ this._teardownCapture();+ this._emit('onError', e);+ return;+ }+ this._ws = ws;+ this._lastText = '';+ const incoming = { tail: Promise.resolve(), pending: 0 };+ this._sendTail = Promise.resolve();+ this._inputEnded = false;+ this._closeEmitted = false;+ this._cancelledBeforeOpen = false;+ ws.binaryType = 'arraybuffer';+ ws.onopen = () => {+ if (this._ws !== ws) { try { ws.close(); } catch {} return; }+ // stop() can run while the browser is still negotiating the socket.+ // In that case opening is only a transport completion, not fresh user+ // consent to start recording. Close immediately and never reacquire+ // capture resources that stop() has already released.+ if (this._pendingClose) {+ this._running = false;+ this._teardownCapture();+ try { this.close(); } catch {}+ return;+ }+ try { if (voiceLog) voiceLog.info('ASR websocket open'); } catch {}+ this._running = true;+ this._emit('onOpen');+ this._startCapture();+ };+ ws.onmessage = (ev) => {+ if (this._ws !== ws) return;+ if (typeof ev.data === 'string') { this._handleJSON(ev.data); return; }+ // Binary gzip decoding is async; browser event dispatch does not+ // wait for it. Keep transcript delivery in this socket's wire order.+ incoming.pending++;+ incoming.tail = incoming.tail.then(() => {+ if (this._ws !== ws) return;+ return this._handleBinary(ev.data, ws);+ }).catch(() => {}).finally(() => { incoming.pending--; });+ };+ ws.onerror = (e) => {+ if (this._ws !== ws) return;+ // Chromium reports close() on a CONNECTING socket through onerror.+ // That is the expected result of the user's explicit cancellation,+ // not an ASR outage that should surface an error dialog.+ if (this._cancelledBeforeOpen) return;+ try { if (voiceLog) voiceLog.error('ASR websocket error', _errorInfo(e)); } catch {}+ // Browser WebSocket error events intentionally omit the HTTP handshake+ // status and usually have no name/message. Preserve a stable,+ // actionable transport category instead of reporting `unknown`.+ const err = new Error('websocket_error');+ err.name = 'WebSocketError';+ err.cause = e;+ this._emit('onError', err);+ };+ ws.onclose = (ev) => {+ if (this._ws !== ws) return;+ try { if (voiceLog) voiceLog.info('ASR websocket close', { code: ev && ev.code, wasClean: ev && ev.wasClean }); } catch {}+ this._captureEpoch++;+ this._inputEnded = true;+ this._running = false;+ this._teardownCapture();+ // Release capture immediately, but an admitted terminal frame must+ // reach the consumer before natural close reports completion.+ const finish = () => {+ if (this._ws !== ws) return;+ this._ws = null;+ this._pendingClose = false;+ this._emitCloseOnce();+ };+ if (incoming.pending) incoming.tail.then(finish);+ else finish();+ };+ }++ _handleJSON(s) {+ let obj;+ try { obj = JSON.parse(String(s || '{}')); } catch { return; }+ if (obj && obj.event === 'timeout') {+ const err = new Error('asr_timeout');+ err.maxSeconds = Number(obj.max_seconds || obj.maxSeconds || 0) || undefined;+ this._emit('onError', err);+ this._running = false;+ this._pendingClose = false;+ return;+ }+ if (obj && obj.event === 'error') {+ const err = new Error('asr_' + (obj.reason || 'error'));+ try { if (voiceLog) voiceLog.error('ASR server event error', { code: _voiceErrorCode(obj.reason) }); } catch {}+ this._emit('onError', err);+ this._running = false;+ this._pendingClose = false;+ return;+ }+ const body = (obj && (obj.payload_msg || obj.body)) || obj || {};+ const result = body.result || body.data || {};+ const text = String(result.text || result.punctuated_text || '');+ this._lastText = text || this._lastText;+ const isLast = !!((obj && obj.is_last_package) || result.last);+ this._emit('onResult', { text: this._lastText, last: isLast });+ if (isLast) {+ this._running = false;+ if (this._pendingClose) { try { this.close(); } catch {} }+ }+ }++ async _handleBinary(ab, ws) {+ const u8 = ab instanceof Uint8Array ? ab : new Uint8Array(ab || []);+ if (!u8 || u8.length < 4) return;+ const headerSize = u8[0] & 0x0f;+ const messageType = u8[1] >> 4;+ const flags = u8[1] & 0x0f;+ const serialization = u8[2] >> 4;+ const compression = u8[2] & 0x0f;+ let idx = headerSize * 4;+ let isLast = false;+ let payloadSize = 0;+ const dv = (off) => new DataView(u8.buffer, u8.byteOffset + off, 4);+ if (flags & 0x01) { idx += 4; } // payload sequence (unused)+ if (flags & 0x02) { isLast = true; }+ if (flags & 0x04) { idx += 4; } // event (unused)+ if (messageType === 9) { payloadSize = dv(idx).getUint32(0, false); idx += 4; }+ else if (messageType === 15) { idx += 4; payloadSize = dv(idx).getUint32(0, false); idx += 4; } // error: code + size+ let payload = u8.subarray(idx, payloadSize ? idx + payloadSize : u8.length);+ if (compression === 1 && HAS_GZIP) {+ try { payload = await gunzipBytes(payload); } catch { return; }+ }+ let obj = null;+ if (serialization === 1) {+ try { obj = JSON.parse(new TextDecoder('utf-8').decode(payload)); } catch {}+ }+ if (this._ws !== ws) return;+ this._handleJSON(JSON.stringify({ is_last_package: isLast, payload_msg: obj }));+ }++ async _sendAudio(bytes, last) {+ const ws = this._ws;+ if (!ws || ws.readyState !== WebSocket.OPEN || this._inputEnded) return;+ if (last) this._inputEnded = true;+ const u8 = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes || []);+ // Compression may finish out of order. Own this socket and keep END+ // behind every audio chunk admitted before stop().+ const pending = this._sendTail.then(async () => {+ if (this._ws !== ws || ws.readyState !== WebSocket.OPEN) return;+ try {+ const payload = this._useGzip ? await gzipBytes(u8) : u8;+ if (this._ws !== ws || ws.readyState !== WebSocket.OPEN) return;+ ws.send(payload);+ if (last) {+ ws.send('__END__');+ this._running = false;+ }+ } catch (e) {+ if (this._ws !== ws || ws.readyState !== WebSocket.OPEN) return;+ try { if (voiceLog) voiceLog.error('ASR audio send failed', _errorInfo(e)); } catch {}+ this._emit('onError', e);+ if (this._ws === ws) this.close();+ }+ });+ this._sendTail = pending;+ return pending;+ }++ async _startCapture() {+ const epoch = this._captureEpoch;+ const ws = this._ws;+ const active = () => this._captureEpoch === epoch && this._ws === ws+ && this._running && !this._pendingClose;+ if (!active()) return;+ try {+ const ms = this._mediaStream;+ 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 (!active()) return;+ this._source = this._audioCtx.createMediaStreamSource(ms);+ this._inRate = this._audioCtx.sampleRate || 48000;+ this._chunkFrames = Math.max(1, Math.floor((this._inRate * this._chunkMs) / 1000));+ let captureReady = false;+ if (this._audioCtx.audioWorklet && typeof window.AudioWorkletNode === 'function') {+ let url = '';+ try {+ const code = `class C extends AudioWorkletProcessor {+ constructor() {+ super();+ this.n = 1024;+ this.b = new Float32Array(this.n);+ this.i = 0;+ this.stopped = false;+ this.port.onmessage = (event) => {+ const data = event.data || {};+ if (data.flush) {+ this.stopped = true;+ if (this.i) {+ const tail = this.b.slice(0, this.i);+ this.i = 0;+ this.port.postMessage({ b: tail }, [tail.buffer]);+ }+ this.port.postMessage({ flushed: true });+ } else if (!this.stopped && typeof data.n === 'number' && data.n > 0) {+ this.n = data.n | 0;+ this.b = new Float32Array(this.n);+ this.i = 0;+ }+ };+ }+ process(inputs, outputs) {+ const audio = inputs && inputs[0] && inputs[0][0];+ const output = outputs && outputs[0] && outputs[0][0];+ if (output) output.fill(0);+ if (this.stopped) return false;+ if (!audio || !audio.length) return true;+ for (let offset = 0; offset < audio.length; offset++) {+ this.b[this.i++] = audio[offset];+ if (this.i >= this.n) {+ const chunk = new Float32Array(this.b);+ this.port.postMessage({ b: chunk }, [chunk.buffer]);+ this.i = 0;+ }+ }+ return true;+ }+}+registerProcessor('orkas-asr-capture', C);`;+ const blob = new Blob([code], { type: 'application/javascript' });+ url = URL.createObjectURL(blob);+ this._workletModuleURL = url;+ await this._audioCtx.audioWorklet.addModule(url);+ if (!active()) return;+ this._workletNode = new AudioWorkletNode(this._audioCtx, 'orkas-asr-capture', {+ numberOfInputs: 1, numberOfOutputs: 1, outputChannelCount: [1],+ });+ const worklet = this._workletNode;+ worklet.port.onmessage = (ev) => {+ if (this._workletNode !== worklet || this._ws !== ws) return;+ const data = ev.data || {};+ if (data.b && (this._running || this._captureFlush)) {+ const samples = data.b instanceof Float32Array ? data.b : new Float32Array(data.b);+ this._sendAudio(this._resampleTo16k(samples, this._inRate), false);+ }+ if (data.flushed && this._captureFlush?.node === worklet) {+ const pending = this._captureFlush;+ this._captureFlush = null;+ pending.resolve(true);+ }+ };+ try { this._workletNode.port.postMessage({ n: this._chunkFrames }); } catch {}+ this._source.connect(this._workletNode);+ this._captureNode = this._workletNode;+ captureReady = true;+ } catch (workletError) {+ if (!active()) return;+ try { if (voiceLog) voiceLog.warn('AudioWorklet capture failed; falling back to ScriptProcessor', _errorInfo(workletError)); } catch {}+ try { if (this._workletNode) this._workletNode.disconnect(); } catch {}+ this._workletNode = null;+ if (this._workletModuleURL) { try { URL.revokeObjectURL(this._workletModuleURL); } catch {} this._workletModuleURL = null; }+ else if (url) { try { URL.revokeObjectURL(url); } catch {} }+ }+ } else {+ try { if (voiceLog) voiceLog.warn('AudioWorklet unavailable; using ScriptProcessor fallback'); } catch {}+ }+ if (!captureReady) {+ const mk = this._audioCtx.createScriptProcessor || this._audioCtx.createJavaScriptNode;+ if (typeof mk !== 'function') throw new Error('audio_capture_unsupported');+ const node = mk.call(this._audioCtx, 4096, 1, 1);+ node.onaudioprocess = (ev) => {+ if (this._scriptNode !== node || this._ws !== ws || !this._running) return;+ const ch = ev.inputBuffer.getChannelData(0);+ this._sendAudio(this._resampleTo16k(ch, this._inRate), false);+ };+ this._source.connect(node);+ this._scriptNode = node;+ this._captureNode = node;+ }+ // Capture-node output must reach the destination or process()/onaudioprocess+ // won't be pumped — route it through a muted gain so nothing is audible.+ this._silentGain = this._audioCtx.createGain();+ try { this._silentGain.gain.value = 0; } catch {}+ this._captureNode.connect(this._silentGain);+ this._silentGain.connect(this._audioCtx.destination);+ } catch (e) {+ if (!active()) return;+ try { if (voiceLog) voiceLog.error('audio capture start failed', _errorInfo(e)); } catch {}+ this._emit('onError', e);+ }+ }++ _releaseMicrophone() {+ const stream = this._mediaStream;+ this._mediaStream = null;+ if (stream) {+ try { stream.getTracks().forEach((track) => { try { track.stop(); } catch {} }); } catch {}+ }+ }++ _teardownCapture() {+ const pending = this._captureFlush;+ this._captureFlush = null;+ if (pending) pending.resolve(false);+ try { if (this._workletNode) this._workletNode.port.onmessage = null; } catch {}+ try { if (this._scriptNode) this._scriptNode.onaudioprocess = null; } catch {}+ try { if (this._workletNode) this._workletNode.disconnect(); } catch {}+ try { if (this._scriptNode) this._scriptNode.disconnect(); } catch {}+ try { if (this._source) this._source.disconnect(); } catch {}+ try { if (this._silentGain) this._silentGain.disconnect(); } catch {}+ try { if (this._audioCtx) { const p = this._audioCtx.close(); if (p && p.then) p.then(() => {}).catch(() => {}); } } catch {}+ this._workletNode = null;+ this._scriptNode = null;+ this._captureNode = null;+ this._source = null;+ this._silentGain = null;+ this._audioCtx = null;+ if (this._workletModuleURL) { try { URL.revokeObjectURL(this._workletModuleURL); } catch {} this._workletModuleURL = null; }+ this._releaseMicrophone();+ }++ _emitCloseOnce() {+ if (this._closeEmitted) return;+ this._closeEmitted = true;+ this._running = false;+ this._emit('onClose');+ }++ _resampleTo16k(f32, inRate) {+ const rate = Math.max(1, inRate || 48000);+ const ratio = rate / 16000;+ const outLen = Math.max(1, Math.floor(f32.length / ratio));+ const u8 = new Uint8Array(outLen * 2);+ const dv = new DataView(u8.buffer);+ for (let i = 0; i < outLen; i++) {+ let s = f32[Math.floor(i * ratio)] || 0;+ if (s > 1) s = 1; else if (s < -1) s = -1;+ dv.setInt16(i * 2, s < 0 ? s * 0x8000 : s * 0x7fff, true);+ }+ return u8;+ }++ stop() {+ if (this._pendingClose) return;+ this._captureEpoch++;+ this._running = false;+ this._pendingClose = true;+ // Release the device now; keep the processor alive only to return its+ // already captured tail. The existing overall close deadline still wins.+ this._releaseMicrophone();+ const ws = this._ws;+ if (!ws) {+ this._teardownCapture();+ this._emitCloseOnce();+ return;+ }+ this._cancelledBeforeOpen = ws.readyState === WebSocket.CONNECTING;+ let flushed = Promise.resolve(true);+ const node = this._workletNode;+ if (node && node.port) {+ flushed = new Promise((resolve) => { this._captureFlush = { node, resolve }; });+ try { node.port.postMessage({ flush: true }); }+ catch {+ this._captureFlush.resolve(false);+ this._captureFlush = null;+ }+ }+ const finish = async () => {+ const complete = await flushed;+ if (this._ws !== ws || !this._pendingClose || ws.readyState === WebSocket.CLOSED) return;+ if (!complete) {+ this._emit('onError', new Error('incomplete_capture'));+ if (this._ws === ws) this.close();+ return;+ }+ this._teardownCapture();+ await this._sendAudio(new Uint8Array(0), true);+ };+ finish();+ // The 1.5s ceiling includes flushing, compression and final transcript.+ try {+ setTimeout(() => {+ if (!this._pendingClose || this._ws !== ws) return;+ if (this._captureFlush) this._emit('onError', new Error('incomplete_capture'));+ if (this._ws === ws) this.close();+ }, 1500);+ } catch {}+ }++ close() {+ this._captureEpoch++;+ this._inputEnded = true;+ this._running = false;+ this._pendingClose = false;+ this._teardownCapture();+ const ws = this._ws;+ this._ws = null;+ try { if (ws) ws.close(); } catch {}+ this._emitCloseOnce();+ }+ }++ // ── Per-composer controller. ─────────────────────────────────────────────+ function _t(key, fallback) {+ try { if (typeof t === 'function') { const v = t(key); if (v && v !== key) return v; } } catch {}+ return fallback;+ }++ function _alert(msg) {+ try { if (typeof uiAlert === 'function') { uiAlert(msg); return; } } catch {}+ try { window.alert(msg); } catch {}+ }++ function _toast(msg) {+ try { if (typeof uiToast === 'function') { uiToast(msg, { variant: 'warning' }); return; } } catch {}+ _alert(msg);+ }++ function _limitMessage(seconds) {+ const n = Number(seconds) || 120;+ return _t('chat.mic_limit_reached', 'Single voice recognition can be up to {seconds} seconds.')+ .replace('{seconds}', String(n));+ }++ function _isPermissionError(name) {+ return /NotAllowed|Permission|denied|SecurityError/i.test(name);+ }++ function _isNoDeviceError(name) {+ return /NotFound|DevicesNotFound/i.test(name);+ }++ function _voiceErrorCode(value) {+ const name = String(value || '').toLowerCase();+ if (/timeout|limit/.test(name)) return 'timeout';+ if (/session_expired/.test(name)) return 'session_expired';+ if (/unauthorized|not_logged|login/.test(name)) return 'unauthorized';+ if (/insufficient_quota|credit/.test(name)) return 'insufficient_quota';+ if (/notallowed|permission|denied|securityerror/.test(name)) return 'permission_denied';+ if (/notfound|devicesnotfound|no_device/.test(name)) return 'no_device';+ if (/chunk_too_large|session_too_large|input_too_large/.test(name)) return 'input_too_large';+ if (/invalid_encoding|invalid_message|malformed|protocol/.test(name)) return 'protocol_error';+ if (/upstream/.test(name)) return 'upstream_error';+ if (/no_url|unavailable/.test(name)) return 'unavailable';+ if (/capture|media_stream|audio/.test(name)) return 'capture_failed';+ if (/websocket|network|socket/.test(name)) return 'network';+ if (/incomplete_transcript/.test(name)) return 'incomplete_transcript';+ if (/empty_transcript/.test(name)) return 'empty_transcript';+ return 'unknown';+ }++ function attach(buttonEl, textareaEl) {+ if (!buttonEl || !textareaEl || buttonEl.dataset.voiceBound === '1') return;+ buttonEl.dataset.voiceBound = '1';+ if (!(window.orkas && window.orkas.voiceInput && typeof window.orkas.voiceInput.createSession === 'function')) {+ // No Server-backed voice support in this build — hide the affordance.+ buttonEl.style.display = 'none';+ return;+ }++ let phase = 'idle'; // 'idle' | 'connecting' | 'recording' | 'finalizing'+ let activeAttempt = null;++ function clearLimitTimer(attempt) {+ if (!attempt) return;+ if (attempt.limitTimer) { try { clearTimeout(attempt.limitTimer); } catch {} }+ attempt.limitTimer = null;+ }++ function startLimitTimer(attempt) {+ clearLimitTimer(attempt);+ attempt.limitTimer = setTimeout(() => {+ attempt.limitTimer = null;+ if (activeAttempt !== attempt || !attempt.client || attempt.phase !== 'recording') return;+ _toast(_limitMessage(120));+ stopRecording({ auto: true });+ }, VOICE_MAX_DURATION_MS);+ }++ 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 === 'recording' || p === 'connecting' || p === 'finalizing')+ ? 'chat.mic_stop_title' : 'chat.mic_title';+ const titleFallback = (p === 'recording' || p === 'connecting' || p === 'finalizing')+ ? 'Stop recording' : 'Voice input';+ buttonEl.title = _t(titleKey, titleFallback);+ buttonEl.setAttribute('aria-label', buttonEl.title);+ }++ function setAttemptPhase(attempt, nextPhase) {+ attempt.phase = nextPhase;+ if (activeAttempt === attempt) setPhase(nextPhase);+ }++ function applyTranscript(attempt, text) {+ if (activeAttempt !== attempt || attempt.cancelled) return;+ const inserted = String(text || '');+ const needsSpace = attempt.before && !/\s$/.test(attempt.before) && inserted ? ' ' : '';+ if (!attempt.insertion?.replace(needsSpace + inserted)) {+ attempt.finished = true;+ reset(attempt);+ try { attempt.client?.close(); } catch {}+ return;+ }+ }++ function reset(attempt) {+ clearLimitTimer(attempt);+ attempt.insertion?.dispose();+ if (activeAttempt !== attempt) return;+ activeAttempt = null;+ setPhase('idle');+ }++ textareaEl.addEventListener('composer-owner-change', () => {+ const attempt = activeAttempt;+ if (!attempt) return;+ attempt.cancelled = true;+ attempt.finished = true;+ reset(attempt);+ try { attempt.client?.close(); } catch {}+ });++ async function startRecording() {+ if (activeAttempt) return;+ const attempt = {+ recordingStarted: false,+ finished: false,+ cancelled: false,+ phase: 'connecting',+ before: composerText(textareaEl).slice(0, composerSelection(textareaEl).start),+ insertion: composerInsertion(textareaEl),+ limitTimer: null,+ client: null,+ };+ activeAttempt = attempt;+ setAttemptPhase(attempt, 'connecting');+ let url = '';+ try {+ const r = await window.orkas.voiceInput.createSession();+ if (activeAttempt !== attempt || attempt.cancelled) return;+ if (r && r.error === 'E_ORKAS_API_KEY_REQUIRED') {+ attempt.finished = true;+ _alert(_t('settings.orkas_api.key_required', 'Enter an API Key first.'));+ reset(attempt);+ return;+ }+ if (!r || r.ok === false || !r.url) throw new Error((r && r.error) || 'no_url');+ url = r.url;+ } catch (e) {+ if (activeAttempt !== attempt || attempt.cancelled) return;+ try { if (voiceLog) voiceLog.error('failed to resolve ASR websocket URL', _errorInfo(e)); } catch {}+ attempt.finished = true;+ _alert(_t('chat.mic_error_unavailable', 'Voice input is unavailable right now.'));+ reset(attempt);+ return;+ }+ if (typeof window.orkas.voiceInput.ensureMicrophoneAccess === 'function') {+ try {+ const access = await window.orkas.voiceInput.ensureMicrophoneAccess();+ if (activeAttempt !== attempt || attempt.cancelled) return;+ if (!access || access.ok === false || !access.granted) {+ attempt.finished = true;+ _alert(_t('chat.mic_error_permission', 'Microphone access was blocked. Allow it in your system settings to use voice input.'));+ reset(attempt);+ return;+ }+ } catch (e) {+ if (activeAttempt !== attempt || attempt.cancelled) return;+ try { if (voiceLog) voiceLog.error('microphone access preflight failed', _errorInfo(e)); } catch {}+ attempt.finished = true;+ _alert(_t('chat.mic_error_unavailable', 'Voice input is unavailable right now.'));+ reset(attempt);+ return;+ }+ }+ if (activeAttempt !== attempt || attempt.cancelled) return;+ if (!attempt.insertion?.valid()) { reset(attempt); return; }+ const attemptClient = new AsrClient(url, {+ onOpen: () => {+ if (activeAttempt !== attempt) return;+ attempt.recordingStarted = true;+ setAttemptPhase(attempt, 'recording');+ startLimitTimer(attempt);+ },+ onResult: ({ text }) => {+ if (activeAttempt !== attempt) return;+ if (text) applyTranscript(attempt, text);+ },+ onError: (err) => {+ if (activeAttempt !== attempt || attempt.finished) {+ try { attemptClient.close(); } catch {}+ return;+ }+ try { if (voiceLog) voiceLog.error('voice client error', { phase: attempt.phase, error: _errorInfo(err) }); } catch {}+ const name = err && typeof err === 'object'+ ? [err.name, err.message].map((value) => String(value || '').trim()).filter(Boolean).join(' ')+ : String(err || '');+ const errorCode = _voiceErrorCode(name);+ attempt.finished = true;+ if (errorCode === 'timeout') {+ _toast(_limitMessage(err && err.maxSeconds));+ } else {+ const permission = errorCode === 'permission_denied' || _isPermissionError(name);+ const noDevice = errorCode === 'no_device' || _isNoDeviceError(name);+ const loggedOut = errorCode === 'unauthorized' || errorCode === 'session_expired';+ const insufficientQuota = errorCode === 'insufficient_quota';+ _alert(loggedOut+ ? _t('settings.orkas_api.key_required', 'Enter an API Key first.')+ : insufficientQuota+ ? _t('chat.mic_insufficient_credits', 'Not enough credits for voice input.')+ : permission+ ? _t('chat.mic_error_permission', 'Microphone access was blocked. Allow it in your system settings to use voice input.')+ : noDevice+ ? _t('chat.mic_error_no_device', 'No microphone was found.')+ : _t('chat.mic_error_unavailable', 'Voice input is unavailable right now.'));+ }+ try { attemptClient.close(); } catch {}+ reset(attempt);+ },+ onClose: () => {+ if (activeAttempt !== attempt) return;+ if (attempt.finished) {+ reset(attempt);+ return;+ }+ reset(attempt);++ },+ });+ attempt.client = attemptClient;+ try {+ await attemptClient.start();+ } catch (e) {+ if (activeAttempt !== attempt || attempt.finished) return;+ try { if (voiceLog) voiceLog.error('voice client start failed', _errorInfo(e)); } catch {}+ attempt.finished = true;+ _alert(_t('chat.mic_error_unavailable', 'Voice input is unavailable right now.'));+ reset(attempt);+ }+ }++ function stopRecording(options) {+ const attempt = activeAttempt;+ if (!attempt || attempt.phase === 'finalizing') return;+ const automatic = !!(options && options.auto);+ attempt.cancelled = !automatic && !attempt.recordingStarted;+ clearLimitTimer(attempt);+ if (attempt.cancelled) {+ const attemptClient = attempt.client;+ attempt.finished = true;+ reset(attempt);+ try { if (attemptClient) attemptClient.stop(); } catch {}+ return;+ }+ setAttemptPhase(attempt, 'finalizing');+ try {+ if (!attempt.client) throw new Error('voice_client_unavailable');+ attempt.client.stop();+ } catch (e) {+ attempt.finished = true;+ reset(attempt);+ }+ }++ buttonEl.addEventListener('click', () => {+ const starting = phase === 'idle' && !activeAttempt;+ if (starting) startRecording();+ else if (activeAttempt) stopRecording();+ });+ setPhase('idle');+ }++ // Expose the transport factory for deterministic capture and cancellation tests.+ window.VoiceInput = { attach, createClient: (url, callbacks) => new AsrClient(url, callbacks) };++ document.addEventListener('DOMContentLoaded', () => {+ attach(document.getElementById('new-chat-mic-btn'), document.getElementById('new-chat-input'));+ attach(document.getElementById('chat-mic-btn'), document.getElementById('chat-input'));+ attach(document.getElementById('project-chat-mic-btn'), document.getElementById('project-chat-input'));+ });+})();diff --git a/test/e2e/voice_input_e2e_lifecycle.spec.ts b/test/e2e/voice_input_e2e_lifecycle.spec.tsnew file mode 100644index 00000000..4aa06085--- /dev/null+++ b/test/e2e/voice_input_e2e_lifecycle.spec.ts@@ -0,0 +1,110 @@+import { expectComposerText } from './fixtures/composer';+import { expect, test as base, OrkasTestApp } from './fixtures/orkas';++import { existsSync, readFileSync, writeFileSync } from 'node:fs';+import { analyzeWebAppLogs } from './fixtures/web-app-log-analysis';++const test = base.extend({+ voiceOrkas: async ({}, use, info) => {+ const previous = process.env.ORKAS_E2E_KEEP_LOGS;+ process.env.ORKAS_E2E_KEEP_LOGS = '1';+ const app = new OrkasTestApp(info, { voiceStub: true });+ try {+ await app.launch();+ await use(app);+ } finally {+ try { await app.dispose(); }+ finally {+ if (previous === undefined) delete process.env.ORKAS_E2E_KEEP_LOGS;+ else process.env.ORKAS_E2E_KEEP_LOGS = previous;+ const log = info.outputPath('electron-main.log');+ expect(existsSync(log), 'Retain complete Electron logs on passing runs too').toBe(true);+ const analysis = analyzeWebAppLogs(readFileSync(log, 'utf8'));+ writeFileSync(info.outputPath('log-analysis.json'), JSON.stringify(analysis, null, 2));+ expect(analysis.passed, 'Review log-analysis.json for errors or incomplete coverage').toBe(true);+ if (analysis.requiresReview) console.warn('Voice E2E log warnings:', JSON.stringify(analysis.findings));+ }+ }+ },+});++async function expectPublicTicketTransport(app: OrkasTestApp): Promise<void> {+ expect(app.voiceSessionRequests).toEqual([{ method: 'POST', path: '/v1/audio/transcription_sessions',+ authorized: true, body: '{}' }]);+ expect(await app.electronApp!.evaluate(() => (globalThis as any).__e2eVoiceSessionUrls))+ .toEqual(['https://orkas.ai/v1/audio/transcription_sessions']);+ const urls = await app.page!.evaluate(() => (window as any).__e2eVoiceSocketUrls);+ expect(urls).toHaveLength(1);+ const socket = new URL(urls[0]);+ expect(socket.origin + socket.pathname).toBe('wss://orkas.ai/api/voice/asr_ws');+ expect(socket.searchParams.get('ticket')).toMatch(/^[A-Za-z0-9_-]{43}$/);+ expect(Array.from(socket.searchParams.keys()).sort()).toEqual(['encoding', 'ticket']);+ expect(await app.page!.locator('#account-login-overlay').count()).toBe(0);+}++test.describe('voice input', () => {+ test('inserts the terminal transcript for review without auto-sending', async ({ voiceOrkas }, info) => {+ if (!voiceOrkas.page) throw new Error('Orkas renderer is unavailable');+ const page = voiceOrkas.page;+ await voiceOrkas.installVoiceCaptureStub();++ const input = page.locator('#new-chat-input');+ const mic = page.locator('#new-chat-mic-btn');+ await input.fill('Draft:');+ await input.evaluate((element: HTMLTextAreaElement) => {+ const w = window as any;+ w.composerSetSelection(element, w.composerText(element).length);+ });++ await mic.click();+ await expect(mic).toHaveClass(/\bis-recording\b/);+ await expect(mic).toHaveAttribute('aria-label', 'Stop recording');+ // A Windows renderer under full-suite load can take slightly over the+ // global 10s expect window to complete the local WebSocket handshake.+ await expect(mic).toHaveAttribute('data-voice-phase', 'recording', { timeout: 20_000 });+ await mic.click();++ await expectComposerText(input, 'Draft: E2E dictated launch note');+ await expect(mic).not.toHaveClass(/\bis-recording\b|\bis-busy\b/);+ await expect(page.locator('#chat-history .chat-message.user')).toHaveCount(0);+ await page.screenshot({ path: info.outputPath('voice-transcript.png') });+ expect(await page.evaluate(() => (window as any).__e2eVoiceTrackStops)).toBe(1);+ await expectPublicTicketTransport(voiceOrkas);+ writeFileSync(info.outputPath('voice-session-requests.json'), JSON.stringify(voiceOrkas.voiceSessionRequests, null, 2));+ });++ test('stopping during socket negotiation never starts a stale recording', async ({ voiceOrkas }, info) => {+ if (!voiceOrkas.page) throw new Error('Orkas renderer is unavailable');+ const page = voiceOrkas.page;+ voiceOrkas.setVoiceMode('blocked-open');+ await voiceOrkas.installVoiceCaptureStub();++ const input = page.locator('#new-chat-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.poll(() => page.evaluate(() => (window as any).__e2eVoiceSocketUrls.length)).toBe(1);+ await mic.click();++ await expect(mic).not.toHaveClass(/\bis-recording\b|\bis-busy\b/);+ await expectComposerText(input, 'Keep this draft');+ await expect(page.locator('.ui-dialog-overlay:visible')).toHaveCount(0);+ expect(await page.evaluate(() => (window as any).__e2eVoiceTrackStops)).toBe(1);+ await expectPublicTicketTransport(voiceOrkas);+ });++ test('requires a user API key without entering an account login flow', async ({ voiceOrkas }, info) => {+ const page = voiceOrkas.page!;+ await voiceOrkas.installVoiceCaptureStub();+ await voiceOrkas.invoke('orkasApi.remove');+ await page.locator('#new-chat-input').fill('Preserve my draft');+ await page.locator('#new-chat-mic-btn').click();+ await expect(page.locator('.ui-dialog-overlay:visible')).toContainText('Enter an API Key first');+ await expectComposerText(page.locator('#new-chat-input'), 'Preserve my draft');+ await expect(page.locator('#account-login-overlay')).toHaveCount(0);+ expect(voiceOrkas.voiceSessionRequests).toHaveLength(0);+ expect(await page.evaluate(() => (window as any).__e2eVoiceSocketUrls)).toEqual([]);+ await page.screenshot({ path: info.outputPath('voice-key-required.png') });+ });+});diff --git a/test/main/features/voice_input.test.ts b/test/main/features/voice_input.test.tsnew file mode 100644index 00000000..78be9087--- /dev/null+++ b/test/main/features/voice_input.test.ts@@ -0,0 +1,72 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const state = vi.hoisted(() => ({ key: 'test-speech-key', uid: 'local-owner' }));+vi.mock('../../../src/main/features/auth', () => ({ getOrkasApiKey: () => state.key }));+vi.mock('../../../src/main/features/users', () => ({ getActiveUserId: () => state.uid }));+vi.mock('electron', () => ({ systemPreferences: {+ getMediaAccessStatus: vi.fn(() => 'granted'), askForMediaAccess: vi.fn(async () => true),+} }));++import { createVoiceSession } from '../../../src/main/features/voice_input';++const ticket = 't'.repeat(43);+describe('API-key voice session', () => {+ beforeEach(() => { state.key = 'test-speech-key'; state.uid = 'local-owner'; });+ afterEach(() => { vi.unstubAllGlobals(); vi.useRealTimers(); });++ it('exchanges a main-process credential for a fixed-origin ticket without exposing the key', async () => {+ const fetcher = vi.fn(async () => new Response(JSON.stringify({ ticket, expires_in: 30, max_seconds: 120 })));+ vi.stubGlobal('fetch', fetcher);+ const result = await createVoiceSession();+ expect(result).toEqual({ ok: true, url: `wss://orkas.ai/api/voice/asr_ws?ticket=${ticket}`, maxSeconds: 120 });+ expect(fetcher).toHaveBeenCalledTimes(1);+ const [url, options] = fetcher.mock.calls[0] as unknown as [string, RequestInit];+ expect(url).toBe('https://orkas.ai/v1/audio/transcription_sessions');+ expect(options).toMatchObject({ method: 'POST', redirect: 'error', body: '{}',+ headers: { Authorization: 'Bearer test-speech-key', 'Content-Type': 'application/json' } });+ expect(options.signal).toBeInstanceOf(AbortSignal);+ expect(JSON.stringify(result)).not.toContain(state.key);+ });++ it('requires a configured key before making any request', async () => {+ state.key = '';+ const fetcher = vi.fn(); vi.stubGlobal('fetch', fetcher);+ expect(await createVoiceSession()).toEqual({ ok: false, error: 'E_ORKAS_API_KEY_REQUIRED' });+ expect(fetcher).not.toHaveBeenCalled();+ });++ it.each([401, 403, 429, 500])('returns a bounded public failure for HTTP %s', async (status) => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response('private upstream error', { status })));+ const result = await createVoiceSession();+ expect(result).toEqual({ ok: false, error: status === 401 || status === 403 ? 'E_ORKAS_API_KEY_REQUIRED' : 'E_VOICE_UNAVAILABLE' });+ expect(JSON.stringify(result)).not.toContain('private');+ });++ it.each([+ { ticket: 'short' }, { ticket: 'x'.repeat(44) }, { ticket: `${'x'.repeat(42)}&` },+ { url: 'wss://untrusted.example/asr', ticket: '' }, { ticket: 123 },+ ])('rejects malformed ticket responses without constructing an arbitrary transport', async (body) => {+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify(body))));+ expect(await createVoiceSession()).toEqual({ ok: false, error: 'E_VOICE_UNAVAILABLE' });+ });++ it.each(['key', 'uid'])('discards a late ticket when the local %s changes', async (field) => {+ let finish!: (response: Response) => void;+ vi.stubGlobal('fetch', vi.fn(() => new Promise<Response>((resolve) => { finish = resolve; })));+ const pending = createVoiceSession();+ state[field as 'key' | 'uid'] = 'replacement';+ finish(new Response(JSON.stringify({ ticket })));+ expect(await pending).toEqual({ ok: false, error: 'E_VOICE_UNAVAILABLE' });+ });++ it('keeps the timeout active until the control response body finishes', async () => {+ vi.useFakeTimers();+ vi.stubGlobal('fetch', vi.fn(async (_url: string, options: RequestInit) => ({+ ok: true, status: 200,+ json: () => new Promise((_resolve, reject) => options.signal!.addEventListener('abort', () => reject(new Error('aborted')), { once: true })),+ })));+ const pending = createVoiceSession();+ await vi.advanceTimersByTimeAsync(60_001);+ expect(await pending).toEqual({ ok: false, error: 'E_VOICE_UNAVAILABLE' });+ });+});diff --git a/test/renderer/voice-input.test.ts b/test/renderer/voice-input.test.tsnew file mode 100644index 00000000..c150bf6c--- /dev/null+++ b/test/renderer/voice-input.test.ts@@ -0,0 +1,890 @@+import { composerAccessorSource } from './composer-test-source';+import { describe, it, expect, vi } from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as vm from 'node:vm';+import { gzipSync, gunzipSync } from 'node:zlib';++function makeButton(id: string) {+ const listeners: Record<string, Function> = {};+ const classes = new Set<string>();+ return {+ id,+ dataset: {} as Record<string, string>,+ style: {} as Record<string, string>,+ title: '',+ classList: {+ toggle(name: string, active: boolean) {+ if (active) classes.add(name);+ else classes.delete(name);+ },+ },+ setAttribute() {},+ addEventListener(name: string, handler: Function) { listeners[name] = handler; },+ click() { return listeners.click?.(); },+ };+}++function makeTextarea() {+ return {+ value: '',+ selectionStart: 0,+ selectionEnd: 0,+ setSelectionRange() {},+ dispatchEvent() {},+ addEventListener() {},+ focus() {},+ };+}++function loadVoiceInput(voice: any, _unused?: undefined, options: {+ sourcePath?: string;+ globals?: Record<string, unknown>;+} = {}) {+ const alerts: string[] = [];+ const windowObject: any = {+ orkas: { voiceInput: voice },+ alert(message: string) { alerts.push(String(message)); },+ };+ const context: any = {+ console,+ window: windowObject,+ document: { addEventListener() {}, getElementById: () => null },+ navigator: {},+ composerInsertion: () => ({ valid: () => true, replace: () => true, dispose() {} }),+ setTimeout,+ clearTimeout,+ URL,+ Date,+ Math,+ Event: class {},+ ...options.globals,+ };+ windowObject.window = windowObject;+ vm.createContext(context);+ vm.runInContext(composerAccessorSource, context);+ const source = fs.readFileSync(options.sourcePath || path.join(__dirname, '../../src/renderer/modules/voice-input.js'), 'utf8');+ vm.runInContext(source, context);+ return { context, alerts };+}++function installAudioCaptureStub(context: any) {+ const node = () => ({ connect() {}, disconnect() {} });+ const captures: any[] = [];+ context.window.AudioContext = class {+ state = 'running';+ sampleRate = 48_000;+ destination = {};+ createMediaStreamSource() { return node(); }+ createScriptProcessor() {+ const capture = { ...node(), onaudioprocess: null };+ captures.push(capture);+ return capture;+ }+ createGain() { return { ...node(), gain: { value: 1 } }; }+ close() { return Promise.resolve(); }+ };+ return captures;+}++function loadCompressedCapture(sourcePath: string, failCompression = false) {+ let releaseFirst: () => void = () => {};+ const first = new Promise<void>((resolve) => { releaseFirst = resolve; });+ let compressions = 0;+ // Driver completion is controlled; compression bytes use real gzip. This+ // exercises capture -> production transport -> wire without a microphone.+ class Compression {+ constructor(_format: string) {+ if (failCompression) throw new Error('synthetic gzip failure');+ }+ }+ class AudioBlob {+ constructor(private parts: Uint8Array[]) {}+ stream() {+ return {+ pipeThrough: () => gzipSync(Buffer.concat(this.parts.map((part) => Buffer.from(part)))),+ };+ }+ }+ class AudioResponse {+ constructor(private bytes: Buffer) {}+ async arrayBuffer() {+ if (++compressions === 1) await first;+ return Uint8Array.from(this.bytes).buffer;+ }+ }+ const { context } = loadVoiceInput({}, undefined, {+ sourcePath,+ globals: { CompressionStream: Compression, DecompressionStream: class {}, Blob: AudioBlob, Response: AudioResponse },+ });+ const sockets: any[] = [];+ class Socket {+ static CONNECTING = 0;+ static OPEN = 1;+ static CLOSED = 3;+ readyState = Socket.CONNECTING;+ frames: (Buffer | string)[] = [];+ onopen?: () => void;+ onclose?: () => void;+ constructor(readonly url: string) { sockets.push(this); }+ open() { this.readyState = Socket.OPEN; this.onopen?.(); }+ 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));+ }+ close() { this.readyState = Socket.CLOSED; this.onclose?.(); }+ }+ context.WebSocket = Socket;+ context.setTimeout = () => 1;+ context.navigator.mediaDevices = {+ getUserMedia: async () => ({ getTracks: () => [{ stop() {} }] }),+ };+ const captures = installAudioCaptureStub(context);+ const errors: Error[] = [];+ const client = context.window.VoiceInput.createClient('wss://example.test/asr', {+ onError: (error: Error) => errors.push(error),+ });+ const capture = (sample: number) => captures.at(-1).onaudioprocess({+ inputBuffer: { getChannelData: () => new Float32Array([sample, sample, sample]) },+ });+ const decode = (frames: (Buffer | string)[]) => frames.map((value) => (+ typeof value === 'string' ? value : Array.from(gunzipSync(value))+ ));+ return { client, sockets, errors, capture, decode, releaseFirst };+}++function loadWorkletCapture(sourcePath: string, options: {+ delayedModule?: boolean;+ delayedPermission?: boolean;+ dropFlush?: boolean;+} = {}) {+ const modules = new Map<string, string>();+ let releaseModule: () => void = () => {};+ const moduleGate = new Promise<void>((resolve) => { releaseModule = resolve; });+ let grantPermission: (value: any) => void = () => {};+ const permission = new Promise((resolve) => { grantPermission = resolve; });+ class WorkletBlob {+ constructor(readonly parts: string[]) {}+ }+ class WorkletURL extends URL {+ static createObjectURL(blob: WorkletBlob) {+ const url = `blob:worklet-${modules.size}`;+ modules.set(url, blob.parts.join(''));+ return url;+ }+ static revokeObjectURL(_url: string) {}+ }+ const { context } = loadVoiceInput({}, undefined, {+ sourcePath, globals: { Blob: WorkletBlob, URL: WorkletURL },+ });+ const nodes: any[] = [];+ const sockets: any[] = [];+ const timers = new Map<number, { callback: () => void; delay: number }>();+ let timerId = 0;+ let tracksStopped = 0;+ let Processor: any;+ let channel: any;+ class WorkletNode {+ port = {+ onmessage: null as any,+ postMessage: (data: any) => {+ if (options.dropFlush && data.flush) return;+ queueMicrotask(() => this.processor.port.onmessage?.({ data }));+ },+ };+ processor: any;+ constructor() {+ channel = this.port;+ this.processor = new Processor();+ nodes.push(this);+ }+ connect() {}+ disconnect() {}+ }+ class CaptureContext {+ state = 'running';+ sampleRate = 16_000;+ destination = {};+ audioWorklet = {+ addModule: async (url: string) => {+ if (options.delayedModule) await moduleGate;+ const source = modules.get(url);+ if (!source) throw new Error('missing owned worklet module');+ vm.runInNewContext(source, {+ AudioWorkletProcessor: class {+ port: any;+ constructor() {+ const owner = channel;+ // Resolve the node's port when it is constructed, after module+ // registration. Production processor messages remain unchanged.+ this.port = {+ onmessage: null,+ postMessage: (data: any) => queueMicrotask(() => owner.onmessage?.({ data })),+ };+ }+ },+ registerProcessor: (_name: string, implementation: any) => { Processor = implementation; },+ });+ },+ };+ createMediaStreamSource() { return { connect() {}, disconnect() {} }; }+ createGain() { return { gain: { value: 1 }, connect() {}, disconnect() {} }; }+ close() { return Promise.resolve(); }+ }+ class Socket {+ static CONNECTING = 0;+ static OPEN = 1;+ static CLOSED = 3;+ readyState = Socket.CONNECTING;+ frames: (Buffer | string)[] = [];+ onopen?: () => void;+ onclose?: () => void;+ constructor(_url: string) { sockets.push(this); }+ open() { this.readyState = Socket.OPEN; this.onopen?.(); }+ send(value: Uint8Array | string) {+ this.frames.push(typeof value === 'string' ? value : Buffer.from(value));+ }+ close() { this.readyState = Socket.CLOSED; this.onclose?.(); }+ }+ const stream = { getTracks: () => [{ stop: () => { tracksStopped++; } }] };+ context.WebSocket = Socket;+ context.AudioWorkletNode = WorkletNode;+ context.window.AudioWorkletNode = WorkletNode;+ context.window.AudioContext = CaptureContext;+ context.navigator.mediaDevices = {+ getUserMedia: () => options.delayedPermission ? permission : Promise.resolve(stream),+ };+ context.setTimeout = (callback: () => void, delay: number) => {+ timers.set(++timerId, { callback, delay });+ return timerId;+ };+ context.clearTimeout = (id: number) => timers.delete(id);+ const errors: Error[] = [];+ const client = context.window.VoiceInput.createClient('wss://example.test/asr', {+ onError: (error: Error) => errors.push(error),+ });+ const processSamples = (count: number) => {+ for (let offset = 0; offset < count; offset += 128) {+ nodes.at(-1).processor.process(+ [[new Float32Array(Math.min(128, count - offset)).fill(0.25)]],+ [[new Float32Array(128)]],+ );+ }+ };+ return {+ client, nodes, sockets, errors, timers, processSamples, releaseModule,+ grantPermission: () => grantPermission(stream),+ tracksStopped: () => tracksStopped,+ };+}++function loadDelayedTranscript(sourcePath: string) {+ let releaseFirst: () => void = () => {};+ const first = new Promise<void>((resolve) => { releaseFirst = resolve; });+ let decodes = 0;+ let tracksStopped = 0;+ class Compression {}+ class Decompression {}+ class IncomingBlob {+ constructor(private parts: Uint8Array[]) {}+ stream() {+ return { pipeThrough: (codec: any) => {+ const input = Buffer.concat(this.parts.map((part) => Buffer.from(part)));+ const incoming = codec instanceof Decompression;+ return { incoming, bytes: incoming ? gunzipSync(input) : gzipSync(input) };+ } };+ }+ }+ class IncomingResponse {+ constructor(private payload: { incoming: boolean; bytes: Buffer }) {}+ async arrayBuffer() {+ if (this.payload.incoming && ++decodes === 1) await first;+ return Uint8Array.from(this.payload.bytes).buffer;+ }+ }+ const { context } = loadVoiceInput({}, undefined, {+ sourcePath,+ globals: {+ CompressionStream: Compression, DecompressionStream: Decompression,+ Blob: IncomingBlob, Response: IncomingResponse, TextDecoder,+ },+ });+ const sockets: any[] = [];+ class Socket {+ static CONNECTING = 0;+ static OPEN = 1;+ static CLOSED = 3;+ readyState = Socket.CONNECTING;+ onopen?: () => void;+ onmessage?: (event: any) => void;+ onclose?: (event: any) => void;+ constructor(_url: string) { sockets.push(this); }+ open() { this.readyState = Socket.OPEN; this.onopen?.(); }+ receive(text: string, terminal = false) {+ const payload = gzipSync(Buffer.from(JSON.stringify({ result: { text } })));+ const frame = Buffer.alloc(12 + payload.length);+ frame.set([0x11, terminal ? 0x93 : 0x91, 0x11, 0]);+ frame.writeInt32BE(terminal ? -2 : 1, 4);+ frame.writeUInt32BE(payload.length, 8);+ payload.copy(frame, 12);+ this.onmessage?.({ data: frame.buffer.slice(frame.byteOffset, frame.byteOffset + frame.length) });+ }+ send() {}+ close() {+ this.readyState = Socket.CLOSED;+ this.onclose?.({ code: 1000, reason: '', wasClean: true });+ }+ }+ context.WebSocket = Socket;+ context.navigator.mediaDevices = {+ getUserMedia: async () => ({ getTracks: () => [{ stop: () => { tracksStopped++; } }] }),+ };+ installAudioCaptureStub(context);+ const timeline: any[] = [];+ const client = context.window.VoiceInput.createClient('wss://example.test/asr', {+ onResult: ({ text, last }: { text: string; last: boolean }) => timeline.push(['result', text, last]),+ onClose: () => timeline.push(['close']),+ onError: (error: Error) => timeline.push(['error', error.message]),+ });+ return { client, sockets, timeline, releaseFirst, tracksStopped: () => tracksStopped };+}++describe.each([+ ['desktop', path.join(__dirname, '../../src/renderer/modules/voice-input.js')],+])('%s compressed transcript ordering', (_platform, sourcePath) => {+ it('delivers partial then terminal text in wire order despite different decode completion times', async () => {+ const fixture = loadDelayedTranscript(sourcePath);+ await fixture.client.start();+ fixture.sockets[0].open();+ fixture.sockets[0].receive('partial');+ fixture.sockets[0].receive('terminal', true);+ await new Promise<void>((resolve) => setImmediate(resolve));+ const whileFirstPending = [...fixture.timeline];+ fixture.releaseFirst();+ await vi.waitFor(() => expect(fixture.timeline).toHaveLength(2));+ expect(whileFirstPending).toEqual([]);+ expect(fixture.timeline).toEqual([['result', 'partial', false], ['result', 'terminal', true]]);+ fixture.client.close();+ });++ it.each([false, true])('delivers terminal before natural close with immediate device release (stopped=%s)', async (stopped) => {+ const fixture = loadDelayedTranscript(sourcePath);+ await fixture.client.start();+ fixture.sockets[0].open();+ if (stopped) {+ fixture.client.stop();+ await new Promise<void>((resolve) => setImmediate(resolve));+ }+ fixture.sockets[0].receive('terminal', true);+ fixture.sockets[0].close(); // The peer closes after sending its final frame.+ await new Promise<void>((resolve) => setImmediate(resolve));+ const whilePending = [...fixture.timeline];+ expect(fixture.tracksStopped()).toBe(1);+ fixture.releaseFirst();+ await vi.waitFor(() => expect(fixture.timeline).toHaveLength(2));+ expect(whilePending).toEqual([]);+ expect(fixture.timeline).toEqual([['result', 'terminal', true], ['close']]);+ });++ it('starts a new recognition without reusing the previous connection transcript', async () => {+ const fixture = loadDelayedTranscript(sourcePath);+ fixture.releaseFirst();+ await fixture.client.start();+ fixture.sockets[0].open();+ fixture.sockets[0].receive('previous recognition', true);+ await vi.waitFor(() => expect(fixture.timeline).toContainEqual(['result', 'previous recognition', true]));+ fixture.client.close();+ await fixture.client.start();+ fixture.sockets[1].open();+ fixture.sockets[1].receive('', true);+ await vi.waitFor(() => expect(fixture.timeline).toHaveLength(3));+ expect(fixture.timeline[2]).toEqual(['result', '', true]);+ fixture.client.close();+ });++ it('discards an explicitly cancelled decode without blocking a replacement connection', async () => {+ const fixture = loadDelayedTranscript(sourcePath);+ await fixture.client.start();+ fixture.sockets[0].open();+ fixture.sockets[0].receive('cancelled terminal', true);+ await new Promise<void>((resolve) => setImmediate(resolve));+ fixture.client.close();+ await fixture.client.start();+ fixture.sockets[1].open();+ fixture.sockets[1].receive('new terminal', true);+ await vi.waitFor(() => expect(fixture.timeline).toContainEqual(['result', 'new terminal', true]));+ fixture.releaseFirst();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(fixture.timeline).toEqual([['close'], ['result', 'new terminal', true]]);+ fixture.client.close();+ });+});++describe.each([+ ['desktop', path.join(__dirname, '../../src/renderer/modules/voice-input.js')],+])('%s worklet capture ownership', (_platform, sourcePath) => {+ it('flushes the final partial 200ms packet before END and releases the microphone immediately', async () => {+ const fixture = loadWorkletCapture(sourcePath);+ await fixture.client.start();+ fixture.sockets[0].open();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(fixture.nodes).toHaveLength(1);+ fixture.processSamples(3840); // Independently specified 240ms at16kHz.+ await new Promise<void>((resolve) => setImmediate(resolve));+ fixture.client.stop();+ expect(fixture.tracksStopped()).toBe(1);+ await vi.waitFor(() => expect(fixture.sockets[0].frames.at(-1)).toBe('__END__'));+ const pcm = Buffer.concat(fixture.sockets[0].frames.filter(Buffer.isBuffer));+ const expected = Buffer.alloc(7680);+ for (let offset = 0; offset < expected.length; offset += 2) expected.writeInt16LE(0x1fff, offset);+ expect(pcm.length).toBe(7680);+ expect(pcm).toEqual(expected);+ expect(fixture.errors).toEqual([]);+ 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();+ fixture.sockets[0].open();+ fixture.client.stop();+ fixture.releaseModule();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(fixture.nodes).toEqual([]);+ expect(fixture.errors).toEqual([]);+ expect(fixture.tracksStopped()).toBe(1);+ fixture.client.close();+ });++ it('releases a late permission grant after close without opening a recording socket', async () => {+ const fixture = loadWorkletCapture(sourcePath, { delayedPermission: true });+ const starting = fixture.client.start();+ fixture.client.close();+ fixture.grantPermission();+ await starting;+ expect(fixture.sockets).toEqual([]);+ expect(fixture.tracksStopped()).toBe(1);+ expect(fixture.errors).toEqual([]);+ });++ it('reports incomplete capture instead of END when the processor never acknowledges flush', async () => {+ const fixture = loadWorkletCapture(sourcePath, { dropFlush: true });+ await fixture.client.start();+ fixture.sockets[0].open();+ await new Promise<void>((resolve) => setImmediate(resolve));+ fixture.processSamples(128);+ fixture.client.stop();+ const deadline = [...fixture.timers.values()].find((timer) => timer.delay === 1500);+ expect(deadline).toBeDefined();+ deadline!.callback();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(fixture.sockets[0].frames).not.toContain('__END__');+ expect(fixture.errors).toHaveLength(1);+ expect(fixture.errors[0].message).toBe('incomplete_capture');+ expect(fixture.tracksStopped()).toBe(1);+ });++ it('cancels a pending flush without a late END or an error after explicit close', async () => {+ const fixture = loadWorkletCapture(sourcePath);+ await fixture.client.start();+ fixture.sockets[0].open();+ await new Promise<void>((resolve) => setImmediate(resolve));+ fixture.processSamples(128);+ fixture.client.stop();+ fixture.client.close();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(fixture.sockets[0].frames).not.toContain('__END__');+ expect(fixture.errors).toEqual([]);+ expect(fixture.tracksStopped()).toBe(1);+ });+});++describe.each([+ ['desktop', path.join(__dirname, '../../src/renderer/modules/voice-input.js')],+])('%s compressed audio transport', (_platform, sourcePath) => {+ it('keeps captured speech in order and sends END only after all accepted audio', async () => {+ const fixture = loadCompressedCapture(sourcePath);+ await fixture.client.start();+ fixture.sockets[0].open();+ fixture.capture(0.25);+ fixture.capture(0.5);+ fixture.client.stop();+ await new Promise<void>((resolve) => setImmediate(resolve));+ const framesWhileFirstPending = [...fixture.sockets[0].frames];+ fixture.releaseFirst();+ await vi.waitFor(() => expect(fixture.sockets[0].frames).toHaveLength(4));++ expect(framesWhileFirstPending).toEqual([]);+ expect(fixture.decode(fixture.sockets[0].frames)).toEqual([+ [0xff, 0x1f], [0xff, 0x3f], [], '__END__',+ ]);+ expect(fixture.errors).toEqual([]);+ fixture.client.close();+ });++ it('discards compression owned by a closed socket without leaking it into a restarted connection', async () => {+ const fixture = loadCompressedCapture(sourcePath);+ await fixture.client.start();+ fixture.sockets[0].open();+ fixture.capture(0.25);+ await new Promise<void>((resolve) => setImmediate(resolve));+ fixture.client.close();+ await fixture.client.start();+ fixture.sockets[1].open();+ fixture.capture(0.5);+ await vi.waitFor(() => expect(fixture.sockets[1].frames).toHaveLength(1));+ fixture.releaseFirst();+ await new Promise<void>((resolve) => setImmediate(resolve));++ expect(fixture.sockets[0].frames).toEqual([]);+ expect(fixture.decode(fixture.sockets[1].frames)).toEqual([[0xff, 0x3f]]);+ expect(fixture.errors).toEqual([]);+ fixture.client.close();+ });++ it('reports compression failure instead of sending raw PCM through a gzip connection', async () => {+ const fixture = loadCompressedCapture(sourcePath, true);+ await fixture.client.start();+ fixture.sockets[0].open();+ fixture.capture(0.25);+ await new Promise<void>((resolve) => setImmediate(resolve));++ expect(fixture.errors).toHaveLength(1);+ expect(fixture.errors[0].message).toBe('synthetic gzip failure');+ expect(fixture.sockets[0].frames).toEqual([]);+ fixture.client.close();+ });+});++describe('voice capture interruption', () => {+ it('does not start capture when the user stops while the socket is connecting', async () => {+ const stoppedTracks: string[] = [];+ const opened: string[] = [];+ const errors: string[] = [];+ let socket: any;+ class FakeWebSocket {+ static CONNECTING = 0;+ static OPEN = 1;+ static CLOSED = 3;+ readyState = FakeWebSocket.CONNECTING;+ binaryType = '';+ onopen: Function | null = null;+ onmessage: Function | null = null;+ onerror: Function | null = null;+ onclose: Function | null = null;++ constructor(_url: string) {+ socket = this;+ }++ send() {}++ close() {+ // Chromium emits an error when a CONNECTING socket is closed by the+ // client. It must remain an intentional cancellation to the UI.+ this.onerror?.({ type: 'error' });+ this.readyState = FakeWebSocket.CLOSED;+ this.onclose?.({ code: 1000, reason: '', wasClean: true });+ }++ open() {+ this.readyState = FakeWebSocket.OPEN;+ this.onopen?.();+ }+ }++ const { context } = loadVoiceInput({+ createSession: async () => ({ ok: true, url: 'wss://example.test/asr' }),+ });+ context.WebSocket = FakeWebSocket;+ context.navigator.mediaDevices = {+ getUserMedia: async () => ({+ getTracks: () => [{ stop: () => stoppedTracks.push('stopped') }],+ }),+ };+ // The close fallback is irrelevant to this deterministic socket and+ // should not keep the test process alive.+ context.setTimeout = () => 1;++ const client = context.window.VoiceInput.createClient('wss://example.test/asr', {+ onOpen: () => opened.push('opened'),+ onError: (error: Error) => errors.push(error.message),+ });+ await client.start();+ client.stop();+ socket.open();++ expect(opened).toEqual([]);+ expect(errors).toEqual([]);+ expect(stoppedTracks).toEqual(['stopped']);+ expect(socket.readyState).toBe(FakeWebSocket.CLOSED);+ });++ it('settles once and releases a late microphone grant after an early stop', async () => {+ let grantMicrophone: Function = () => {};+ const stoppedTracks: string[] = [];+ const closed: string[] = [];+ const { context } = loadVoiceInput({+ createSession: async () => ({ ok: true, url: 'wss://example.test/asr' }),+ });+ context.navigator.mediaDevices = {+ getUserMedia: () => new Promise((resolve) => { grantMicrophone = resolve; }),+ };+ context.setTimeout = () => 1;++ const client = context.window.VoiceInput.createClient('wss://example.test/asr', {+ onClose: () => closed.push('closed'),+ });+ const starting = client.start();+ client.stop();+ grantMicrophone({+ getTracks: () => [{ stop: () => stoppedTracks.push('stopped') }],+ });+ await starting;++ expect(closed).toEqual(['closed']);+ expect(stoppedTracks).toEqual(['stopped']);+ });+});+++// Controller tests keep ticket, microphone and socket boundaries deterministic;+// the capture/wire cases above own audio framing. No account or telemetry facade.+function controllerHarness(voiceOverrides: Record<string, unknown> = {}) {+ const voice = {+ createSession: vi.fn(async () => ({ ok: true, url: 'wss://example.test/asr?ticket=one-use' })),+ ensureMicrophoneAccess: vi.fn(async () => ({ ok: true, granted: true })),+ ...voiceOverrides,+ };+ const { context, alerts } = loadVoiceInput(voice);+ const sockets: any[] = [];+ const stopped = vi.fn();+ const send = vi.fn();+ const timers = new Map<number, Function>();+ let nextTimer = 0;+ context.setTimeout = (callback: Function) => { timers.set(++nextTimer, callback); return nextTimer; };+ context.clearTimeout = (id: number) => timers.delete(id);+ context.sendMessage = send;+ context.sendNewChat = send;+ const listeners: Record<string, Function> = {};+ const textarea = { ...makeTextarea(), value: 'Keep this draft', selectionStart: 15, selectionEnd: 15,+ addEventListener: (name: string, callback: Function) => { listeners[name] = callback; },+ dispatchEvent: vi.fn(),+ };+ let valid = true;+ const replacements: string[] = [];+ context.composerInsertion = () => {+ const from = textarea.selectionStart;+ let to = textarea.selectionEnd;+ let disposed = false;+ return {+ valid: () => valid && !disposed,+ replace(text: string) {+ if (!valid || disposed) return false;+ replacements.push(text);+ textarea.value = textarea.value.slice(0, from) + text + textarea.value.slice(to);+ to = from + text.length;+ return true;+ },+ dispose() { disposed = true; },+ };+ };+ class Socket {+ static CONNECTING = 0; static OPEN = 1; static CLOSED = 3;+ readyState = Socket.CONNECTING;+ onopen: Function | null = null; onmessage: Function | null = null;+ onerror: Function | null = null; onclose: Function | null = null;+ send = 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?.(); }+ result(text: string, last = false) { this.onmessage?.({data:JSON.stringify({result:{text,last}})}); }+ error(reason: string) { this.onmessage?.({data:JSON.stringify({event:'error',reason})}); }+ }+ context.WebSocket = Socket;+ const capture = vi.fn(async () => ({getTracks: () => [{stop:stopped}]}));+ context.navigator.mediaDevices = {getUserMedia:capture};+ installAudioCaptureStub(context);+ const button = makeButton('chat-mic-btn');+ context.window.VoiceInput.attach(button, textarea);+ const settle = async () => { for (let i = 0; i < 8; i++) await Promise.resolve(); };+ const start = async () => { button.click(); await settle(); };+ const ownerChange = () => listeners['composer-owner-change']?.();+ return { context, voice, alerts, button, textarea, sockets, capture, stopped, send,+ replacements, timers, start, settle, ownerChange, invalidate: () => { valid = false; } };+}++describe('voice input controller ticket and composer ownership', () => {+ it('requests an API key without capturing audio or changing the draft', async () => {+ const h = controllerHarness({createSession:vi.fn(async () => ({ok:false,error:'E_ORKAS_API_KEY_REQUIRED'}))});+ await h.start();+ expect(h.alerts).toEqual(['Enter an API Key first.']);+ expect(h.voice.ensureMicrophoneAccess).not.toHaveBeenCalled();+ expect(h.capture).not.toHaveBeenCalled();+ expect(h.sockets).toEqual([]);+ expect(h.textarea.value).toBe('Keep this draft');+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.send).not.toHaveBeenCalled();+ });++ it('honors microphone preflight denial before capture and leaves the draft editable', async () => {+ const h = controllerHarness({ensureMicrophoneAccess:vi.fn(async () => ({ok:false,granted:false}))});+ await h.start();+ expect(h.alerts).toEqual(['Microphone access was blocked. Allow it in your system settings to use voice input.']);+ expect(h.capture).not.toHaveBeenCalled();+ expect(h.sockets).toEqual([]);+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.textarea.value).toBe('Keep this draft');+ });++ it('reports rejected ticket requests without exposing server errors or consuming the draft', async () => {+ const h = controllerHarness({createSession:vi.fn(async () => { throw new Error('private-ticket-url-and-key'); })});+ await h.start();+ expect(h.alerts).toEqual(['Voice input is unavailable right now.']);+ expect(h.capture).not.toHaveBeenCalled();+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.textarea.value).toBe('Keep this draft');+ });++ it('cancels a pending ticket and permits a new attempt while the old response is outstanding', async () => {+ let resolveTicket: Function = () => {};+ const request = vi.fn().mockImplementationOnce(() => new Promise(resolve => { resolveTicket = resolve; }))+ .mockResolvedValue({ok:true,url:'wss://example.test/asr?ticket=new'});+ const h = controllerHarness({createSession:request});+ await h.start();+ h.button.click();+ expect(h.button.dataset.voicePhase).toBe('idle');+ await h.start();+ expect(h.sockets).toHaveLength(1);+ resolveTicket({ok:true,url:'wss://example.test/asr?ticket=stale'});+ await h.settle();+ expect(h.sockets).toHaveLength(1);+ expect(h.sockets[0].url).toContain('ticket=new');+ expect(h.capture).toHaveBeenCalledTimes(1);+ expect(h.button.dataset.voicePhase).toBe('connecting');+ expect(h.alerts).toEqual([]);+ h.ownerChange();+ });++ it('abandons pending microphone preflight when the user stops', async () => {+ let allow: Function = () => {};+ const h = controllerHarness({ensureMicrophoneAccess:vi.fn(() => new Promise(resolve => {allow=resolve;}))});+ await h.start();+ h.button.click();+ allow({ok:true,granted:true});+ await h.settle();+ expect(h.capture).not.toHaveBeenCalled();+ expect(h.sockets).toEqual([]);+ expect(h.alerts).toEqual([]);+ expect(h.button.dataset.voicePhase).toBe('idle');+ });++ it('does not attach an outstanding ticket to a new composer owner', async () => {+ let resolveTicket: Function = () => {};+ const h = controllerHarness({createSession:vi.fn(() => new Promise(resolve => {resolveTicket=resolve;}))});+ await h.start();+ h.ownerChange();+ h.textarea.value = 'Other task draft';+ resolveTicket({ok:true,url:'wss://example.test/asr?ticket=stale'});+ await h.settle();+ expect(h.capture).not.toHaveBeenCalled();+ expect(h.sockets).toEqual([]);+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.textarea.value).toBe('Other task draft');+ });++ it('closes recording on owner changes and ignores late transcripts', async () => {+ const h = controllerHarness();+ await h.start();+ const socket = h.sockets[0]; socket.open();+ h.ownerChange();+ h.textarea.value = 'New owner draft';+ socket.result('stale transcript', true);+ expect(socket.close).toHaveBeenCalledTimes(1);+ expect(h.stopped).toHaveBeenCalledTimes(1);+ expect(h.replacements).toEqual([]);+ expect(h.textarea.value).toBe('New owner draft');+ expect(h.timers.size).toBe(0);+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.send).not.toHaveBeenCalled();+ });++ it('ignores a prior socket close while a later attempt is connecting', async () => {+ const h = controllerHarness();+ await h.start();+ const old = h.sockets[0];+ h.button.click();+ await h.start();+ const current = h.sockets[1];+ old.onclose?.({code:1000});+ expect(h.button.dataset.voicePhase).toBe('connecting');+ expect(current.close).not.toHaveBeenCalled();+ expect(h.alerts).toEqual([]);+ current.open();+ expect(h.button.dataset.voicePhase).toBe('recording');+ h.ownerChange();+ });++ it('recovers from socket handshake failure with no raw ticket error in the UI', async () => {+ const h = controllerHarness();+ await h.start();+ h.sockets[0].onerror?.({type:'error',message:'private-ticket'});+ expect(h.alerts).toEqual(['Voice input is unavailable right now.']);+ expect(h.stopped).toHaveBeenCalledTimes(1);+ expect(h.sockets[0].close).toHaveBeenCalledTimes(1);+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.textarea.value).toBe('Keep this draft');+ });++ it.each([['session_expired','Enter an API Key first.'],+ ['insufficient_quota','Not enough credits for voice input.']])('keeps %s failures recoverable without sending', async (reason,message) => {+ const h = controllerHarness();+ await h.start(); h.sockets[0].open(); h.sockets[0].error(reason);+ expect(h.alerts).toEqual([message]);+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.stopped).toHaveBeenCalledTimes(1);+ expect(h.timers.size).toBe(0);+ expect(h.textarea.value).toBe('Keep this draft');+ expect(h.send).not.toHaveBeenCalled();+ });++ it('retains a partial transcript for review if the socket closes before a terminal result', async () => {+ const h = controllerHarness();+ await h.start(); const socket = h.sockets[0]; socket.open();+ socket.result('partial words');+ socket.close(); await h.settle();+ expect(h.textarea.value).toBe('Keep this draft partial words');+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.stopped).toHaveBeenCalledTimes(1);+ expect(h.send).not.toHaveBeenCalled();+ expect(h.textarea.dispatchEvent).not.toHaveBeenCalled();+ });++ it('replaces the owned transcript range and keeps final words for explicit send', async () => {+ const h = controllerHarness();+ await h.start(); const socket = h.sockets[0]; socket.open();+ socket.result('first words');+ h.button.click();+ expect(h.button.dataset.voicePhase).toBe('finalizing');+ socket.result('corrected final words',true); await h.settle();+ expect(h.textarea.value).toBe('Keep this draft corrected final words');+ expect(h.replacements).toEqual([' first words',' corrected final words']);+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.stopped).toHaveBeenCalledTimes(1);+ expect(h.send).not.toHaveBeenCalled();+ expect(h.textarea.dispatchEvent).not.toHaveBeenCalled();+ expect(h.alerts).toEqual([]);+ });++ it('does not overwrite a range invalidated by an intervening user edit', async () => {+ const h = controllerHarness();+ await h.start(); const socket = h.sockets[0]; socket.open();+ h.invalidate(); h.textarea.value = 'Manually corrected draft';+ socket.result('late words',true);+ expect(h.textarea.value).toBe('Manually corrected draft');+ expect(h.replacements).toEqual([]);+ expect(h.button.dataset.voicePhase).toBe('idle');+ expect(h.stopped).toHaveBeenCalledTimes(1);+ expect(h.send).not.toHaveBeenCalled();+ });+});