The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(remote): voice over remote, push to talk and hands free (GH #212)
purple9b8fcb32fdee
diff --git a/mobile-client/client.js b/mobile-client/client.jsindex 6675f299..424fd9ea 100644--- a/mobile-client/client.js+++ b/mobile-client/client.js@@ -61,6 +61,7 @@ import {var ICON_SVG_OPEN = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">';var ICON_SVG_CLOSE = '</svg>';var ICONS = {+ mic:'<rect x="9" y="2" width="6" height="12" rx="3"/><path d="M19 10v2a7 7 0 0 1-14 0v-2"/><line x1="12" y1="19" x2="12" y2="22"/>',menu:'<line x1="3" y1="6" x2="21" y2="6"/><line x1="3" y1="12" x2="21" y2="12"/><line x1="3" y1="18" x2="21" y2="18"/>',close:'<line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>',add:'<line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/>',@@ -727,6 +728,7 @@ import {// route to the right action.(function(){var busy = streaming || agentRunning;+ if(!busy && voiceMicShown()) return micButtonHtml();var btnCls = busy ? 'send-btn cancel' : 'send-btn';var handler = busy ? 'window._cancelSend()' : 'window._doSend()';var label = busy ? 'Stop' : 'Send';@@ -742,6 +744,7 @@ import {setupFileInput();renderChat();renderAttachments();+ voiceSlot();}// ── Drawer ──@@ -833,7 +836,7 @@ import {function setupInput(){var inp = el('msg-input');if(!inp) return;- inp.addEventListener('input', function(){inp.style.height='auto';inp.style.height=Math.min(inp.scrollHeight,220)+'px';});+ inp.addEventListener('input', function(){inp.style.height='auto';inp.style.height=Math.min(inp.scrollHeight,220)+'px';voiceSlot();});inp.addEventListener('keydown', function(e){if(e.key==='Enter'&&!e.shiftKey&&!e.isComposing){e.preventDefault();window._doSend();}});}@@ -876,7 +879,7 @@ import {function renderAttachments(){var row = el('img-preview-row');if(!row) return;- if(!pendingImages.length){ row.style.display='none'; row.innerHTML=''; return; }+ if(!pendingImages.length){ row.style.display='none'; row.innerHTML=''; voiceSlot(); return; }row.style.display='flex';var html = '';for(var i=0;i<pendingImages.length;i++){@@ -887,6 +890,7 @@ import {'</div>';}row.innerHTML = html;+ voiceSlot();}// ── Plan strip (todo_write) ───────────────────────────────────@@ -2221,6 +2225,7 @@ import {var finalText = target ? (target.content || '') : '';postChatEvent('assistant', finalText);syncCurrentChat();+ voiceAnswerDone();}step();@@ -2337,5 +2342,477 @@ import {// disabled button.renderShell();renderChat();+ voiceAnswerDone();}+ // ── Voice over remote (GitHub #212) ─────────────────────────────+ // The same two ways as in the LU app (src/mobile/screens/remote/parts/+ // RemoteVoice.tsx): hold the microphone to talk and let go to send, or+ // tap it for hands free, where this page hears the end of a sentence by+ // itself, reads the answer aloud and listens again until End. The+ // computer writes the take down (/remote-api/voice/transcribe), the text+ // goes into the chat like a typed message. The answer is read with the+ // voice of this phone, else with the voice of the computer.+ //+ // A browser hands out the microphone only on a secure page. Over the+ // plain Wi-Fi address it is not one, so there the microphone says that+ // once and points to the LU app or the keyboard's own dictation.+ var VOICE_SPEECH_LEVEL = 0.1;+ var VOICE_QUIET_LEVEL = 0.05;+ var VOICE_SPEECH_MIN_MS = 250;+ var VOICE_END_QUIET_MS = 1100;+ var VOICE_GIVE_UP_MS = 30000;+ var VOICE_HOLD_MS = 300;+ var VOICE_MIN_TAKE_MS = 400;+ var VOICE_TEXT = {+ mic: 'Talk to your computer. Hold to talk, tap for hands free',+ listening: 'Listening',+ talk: 'Talk, let go to send',+ quiet: 'Nothing heard so far',+ sending: 'Your computer writes it down',+ waiting: 'LU is answering',+ speaking: 'Reading the answer',+ interrupt: 'Tap to talk',+ end: 'End',+ ok: 'OK',+ insecure: 'This browser gives the microphone only to a secure page, and the Wi-Fi address is not one. Talk in the LU app, or use the microphone of your keyboard.',+ denied: 'The browser has no access to the microphone. Allow it for this page.',+ nothing: 'Nothing was heard. Hold the microphone a little longer.',+ gaveUp: 'Hands free ended after a long silence.',+ failed: 'The computer could not write down what you said.',+ speakFailed: 'The answer could not be read aloud.'+ };+ var voiceFeature = false;+ var voice = { phase: 'off', mode: null, since: 0, downAt: 0, pendingUp: null, rec: null, token: 0, turn: null, timer: null, heard: false, caps: null, capsAt: 0, answerBefore: null, note: '', audio: null };++ function voiceSecure(){+ try{ return !!(window.isSecureContext && navigator.mediaDevices && navigator.mediaDevices.getUserMedia); }catch(_){ return false; }+ }++ // Ask once whether the computer offers voice at all (feature `voice`).+ fetch('/remote-api/status/full',{headers:{'Authorization':'Bearer '+TOKEN}})+ .then(absorbRefresh)+ .then(function(r){ return r.ok ? r.json() : null; })+ .then(function(s){+ var f = s && Array.isArray(s.features) ? s.features : [];+ voiceFeature = f.indexOf('voice') >= 0;+ voiceSlot();+ })+ .catch(function(){});++ function voiceCaps(){+ if(voice.caps && Date.now() - voice.capsAt < 30000) return Promise.resolve(voice.caps);+ return fetch('/remote-api/voice',{headers:{'Authorization':'Bearer '+TOKEN}})+ .then(absorbRefresh)+ .then(function(r){ if(r.status===401){clearAuthAndReload();throw new Error('401');} return r.json(); })+ .then(function(c){ voice.caps = c || {}; voice.capsAt = Date.now(); return voice.caps; });+ }++ /** Does the shared slot show the microphone: an empty field, nothing running, the computer offers voice. */+ function voiceMicShown(){+ if(!voiceFeature || streaming || agentRunning) return false;+ if(voice.phase === 'recording' || voice.phase === 'sending') return true;+ var inp = el('msg-input');+ return !(inp && inp.value.trim()) && !pendingImages.length;+ }++ function micButtonHtml(){+ return '<button class="send-btn mic'+(voice.phase==='recording'?' live':'')+'" id="send-btn" aria-label="'+H(VOICE_TEXT.mic)+'" title="'+H(VOICE_TEXT.mic)+'"'+(voice.phase==='sending'?' disabled':'')+'><span class="material-symbols-outlined">'+svgIcon('mic')+'</span></button>';+ }++ /** Swap Send and the microphone in place, as the field fills and empties. */+ function voiceSlot(){+ var btn = el('send-btn');+ if(!btn || streaming || agentRunning) return;+ var wantMic = voiceMicShown();+ var isMic = btn.classList.contains('mic');+ if(wantMic !== isMic){+ var wrap = document.createElement('div');+ wrap.innerHTML = wantMic ? micButtonHtml() :+ '<button class="send-btn" id="send-btn" onclick="window._doSend()" aria-label="Send" title="Send"><span class="material-symbols-outlined">'+svgIcon('arrow_upward')+'</span></button>';+ btn.parentNode.replaceChild(wrap.firstChild, btn);+ btn = el('send-btn');+ }+ if(wantMic) bindMic(btn);+ voiceLine();+ }++ function bindMic(btn){+ if(btn._voiceBound) return;+ btn._voiceBound = true;+ var pressed = false;+ btn.addEventListener('pointerdown', function(e){+ if(e.button !== 0) return;+ e.preventDefault();+ try{ btn.setPointerCapture(e.pointerId); }catch(_){}+ pressed = true;+ voiceDown();+ });+ var up = function(){ if(!pressed) return; pressed = false; voiceUp(); };+ btn.addEventListener('pointerup', up);+ btn.addEventListener('pointercancel', up);+ btn.addEventListener('contextmenu', function(e){ e.preventDefault(); });+ btn.addEventListener('click', function(e){ if(e.detail === 0){ voiceDown(); voiceUp(); } });+ }++ /** The line in place of the text field while a turn runs. */+ function voiceLine(){+ var row = document.querySelector('.input-row');+ var inp = el('msg-input');+ if(!row || !inp) return;+ var line = el('voice-line');+ if(voice.phase === 'off' && !voice.note){+ if(line) line.parentNode.removeChild(line);+ inp.style.display = '';+ return;+ }+ if(!line){+ line = document.createElement('div');+ line.id = 'voice-line';+ line.className = 'voice-line';+ line.setAttribute('role','status');+ row.insertBefore(line, inp);+ }+ inp.style.display = 'none';+ line.setAttribute('data-state', voice.note ? 'note' : voice.phase);+ line.setAttribute('data-mode', voice.mode || 'pending');+ var end = '<button class="voice-end" type="button" id="voice-end">'+H(voice.note ? VOICE_TEXT.ok : VOICE_TEXT.end)+'</button>';+ var html;+ if(voice.note){+ html = '<span class="voice-hint voice-note">'+H(voice.note)+'</span>' + end;+ } else if(voice.phase === 'recording'){+ html = '<span class="voice-bars" id="voice-bars" aria-hidden="true"><i></i><i></i><i></i><i></i><i></i></span>' ++ '<span class="voice-clock" id="voice-clock">0:00</span>' ++ '<span class="voice-hint" id="voice-hint">'+H(voice.mode==='free' ? VOICE_TEXT.listening : VOICE_TEXT.talk)+'</span>' ++ (voice.mode === 'free' ? end : '');+ } else if(voice.phase === 'speaking'){+ html = '<button class="voice-tap" type="button" id="voice-interrupt"><span class="voice-hint">'+H(VOICE_TEXT.speaking)+'</span><span class="voice-sub">'+H(VOICE_TEXT.interrupt)+'</span></button>' + end;+ } else {+ html = '<span class="voice-spin" aria-hidden="true"></span><span class="voice-hint">'+H(voice.phase==='sending' ? VOICE_TEXT.sending : VOICE_TEXT.waiting)+'</span>' + end;+ }+ line.innerHTML = html;+ var e = el('voice-end'); if(e) e.onclick = function(){ voice.note = ''; voiceEnd(); };+ var it = el('voice-interrupt'); if(it) it.onclick = voiceInterrupt;+ }++ function voiceTell(text){+ voiceEnd();+ voice.note = text;+ voiceLine();+ }++ function voiceStopListening(){+ if(voice.timer){ clearInterval(voice.timer); voice.timer = null; }+ voice.turn = null;+ }++ function voiceEnd(){+ voice.token++;+ voiceStopListening();+ if(voice.rec){ try{ voice.rec.cancel(); }catch(_){} voice.rec = null; }+ voice.pendingUp = null;+ try{ if(window.speechSynthesis) window.speechSynthesis.cancel(); }catch(_){}+ if(voice.audio){ try{ voice.audio.pause(); }catch(_){} voice.audio = null; }+ voice.phase = 'off';+ voice.mode = null;+ voiceSlot();+ voiceLine();+ }++ /** The microphone: a recorder with its level, the take as 16 kHz mono WAV. */+ function voiceOpenRecorder(){+ return navigator.mediaDevices.getUserMedia({audio:{echoCancellation:true,noiseSuppression:true,autoGainControl:true}}).then(function(stream){+ var Ctx = window.AudioContext || window.webkitAudioContext;+ var ctx = new Ctx();+ var src = ctx.createMediaStreamSource(stream);+ var an = ctx.createAnalyser(); an.fftSize = 256; src.connect(an);+ var proc = ctx.createScriptProcessor(4096, 1, 1);+ var mute = ctx.createGain(); mute.gain.value = 0;+ src.connect(proc); proc.connect(mute); mute.connect(ctx.destination);+ var chunks = [];+ proc.onaudioprocess = function(e){ chunks.push(new Float32Array(e.inputBuffer.getChannelData(0))); };+ if(ctx.state === 'suspended'){ try{ ctx.resume(); }catch(_){} }+ var buf = new Uint8Array(an.fftSize);+ var level = 0;+ var close = function(){+ try{ proc.disconnect(); src.disconnect(); mute.disconnect(); }catch(_){}+ try{ stream.getTracks().forEach(function(t){ t.stop(); }); }catch(_){}+ try{ ctx.close(); }catch(_){}+ };+ return {+ level: function(){+ an.getByteTimeDomainData(buf);+ var s = 0;+ for(var i = 0; i < buf.length; i++){ var v = (buf[i]-128)/128; s += v*v; }+ var now = Math.min(1, Math.sqrt(s/buf.length)*4);+ level = now >= level ? now : level*0.6 + now*0.4;+ return level;+ },+ stop: function(){ close(); return voiceWav(chunks, ctx.sampleRate); },+ cancel: close+ };+ });+ }++ function voiceWav(chunks, rate){+ var total = 0, i, j;+ for(i = 0; i < chunks.length; i++) total += chunks[i].length;+ var target = 16000;+ var ratio = rate > target ? rate/target : 1;+ var outLen = Math.floor(total/ratio);+ var out = new Int16Array(outLen);+ var all = new Float32Array(total), o = 0;+ for(i = 0; i < chunks.length; i++){ all.set(chunks[i], o); o += chunks[i].length; }+ for(j = 0; j < outLen; j++){+ var a = Math.floor(j*ratio), b = Math.min(total, Math.floor((j+1)*ratio)), s = 0;+ for(i = a; i < b; i++) s += all[i];+ var v = b > a ? s/(b-a) : all[a] || 0;+ v = Math.max(-1, Math.min(1, v));+ out[j] = v < 0 ? v*0x8000 : v*0x7fff;+ }+ var outRate = ratio > 1 ? target : rate;+ var buffer = new ArrayBuffer(44 + out.length*2);+ var view = new DataView(buffer);+ var w = function(off, s){ for(var k = 0; k < s.length; k++) view.setUint8(off+k, s.charCodeAt(k)); };+ w(0,'RIFF'); view.setUint32(4, 36 + out.length*2, true); w(8,'WAVE'); w(12,'fmt ');+ view.setUint32(16,16,true); view.setUint16(20,1,true); view.setUint16(22,1,true);+ view.setUint32(24,outRate,true); view.setUint32(28,outRate*2,true); view.setUint16(32,2,true); view.setUint16(34,16,true);+ w(36,'data'); view.setUint32(40, out.length*2, true);+ for(j = 0; j < out.length; j++) view.setInt16(44 + j*2, out[j], true);+ return new Blob([view], {type:'audio/wav'});+ }++ function voiceStartTake(token){+ return voiceOpenRecorder().then(function(rec){+ if(token !== voice.token){ rec.cancel(); return false; }+ voice.rec = rec;+ voice.since = Date.now();+ voice.heard = false;+ voice.phase = 'recording';+ voiceSlot();+ voiceLine();+ // The bars and the clock, ten times a second; hands free also watches for the end of a sentence.+ voice.timer = setInterval(function(){ voiceTick(token); }, 90);+ return true;+ }, function(err){+ if(token !== voice.token) return false;+ voiceTell(err && (err.name === 'NotAllowedError' || err.name === 'SecurityError') ? VOICE_TEXT.denied : VOICE_TEXT.insecure);+ return false;+ });+ }++ function voiceTick(token){+ if(token !== voice.token || !voice.rec) return;+ var now = Date.now();+ var level = voice.rec.level();+ if(level >= VOICE_SPEECH_LEVEL) voice.heard = true;+ var bars = el('voice-bars');+ if(bars){+ var weights = [0.55,0.85,1,0.8,0.5];+ for(var i = 0; i < bars.children.length; i++) bars.children[i].style.transform = 'scaleY('+Math.max(0.15, Math.min(1, level*weights[i]*1.6)).toFixed(2)+')';+ }+ var clock = el('voice-clock');+ if(clock){ var s = Math.floor((now - voice.since)/1000); clock.textContent = Math.floor(s/60)+':'+('0'+(s%60)).slice(-2); }+ var hint = el('voice-hint');+ if(hint && !voice.heard && now - voice.since > 3000) hint.textContent = VOICE_TEXT.quiet;+ else if(hint && voice.heard) hint.textContent = voice.mode === 'free' ? VOICE_TEXT.listening : VOICE_TEXT.talk;+ if(voice.mode !== 'free' || !voice.turn) return;+ var t = voice.turn;+ if(!t.heard){+ if(level >= VOICE_SPEECH_LEVEL){+ if(t.loudSince === null) t.loudSince = now;+ if(now - t.loudSince >= VOICE_SPEECH_MIN_MS){ t.heard = true; t.quietSince = null; }+ } else {+ if(level < VOICE_QUIET_LEVEL) t.loudSince = null;+ if(now - t.since >= VOICE_GIVE_UP_MS){ voiceTell(VOICE_TEXT.gaveUp); }+ }+ return;+ }+ if(level >= VOICE_QUIET_LEVEL){ t.quietSince = null; return; }+ if(t.quietSince === null) t.quietSince = now;+ if(now - t.quietSince >= VOICE_END_QUIET_MS) voiceFinish(token);+ }++ function voiceListenFree(token){+ voice.mode = 'free';+ voice.turn = { since: Date.now(), loudSince: null, heard: false, quietSince: null };+ voiceLine();+ }++ function voiceListenAgain(token){+ if(token !== voice.token) return;+ voiceStartTake(token).then(function(ok){ if(ok) voiceListenFree(token); });+ }++ function voiceFinish(token){+ if(token !== voice.token || !voice.rec) return;+ var rec = voice.rec; voice.rec = null;+ voiceStopListening();+ var free = voice.mode === 'free';+ var long = Date.now() - voice.since >= VOICE_MIN_TAKE_MS;+ var wav = rec.stop();+ if(!free && !long){ voiceTell(VOICE_TEXT.nothing); return; }+ voice.phase = 'sending';+ voiceSlot(); voiceLine();+ fetch('/remote-api/voice/transcribe',{method:'POST',headers:{'Authorization':'Bearer '+TOKEN,'Content-Type':'audio/wav'},body:wav})+ .then(absorbRefresh)+ .then(function(r){+ if(r.status===401){clearAuthAndReload();throw new Error('401');}+ return r.json().catch(function(){ return {}; }).then(function(b){ return {ok: r.ok, body: b || {}}; });+ })+ .then(function(a){+ if(token !== voice.token) return;+ if(!a.ok){ voice.caps = null; voiceTell(a.body.message || VOICE_TEXT.failed); return; }+ var text = String(a.body.text || '').trim();+ if(!text){ if(free) return voiceListenAgain(token); voiceTell(VOICE_TEXT.nothing); return; }+ var last = voiceLastAnswer();+ voice.answerBefore = last ? last.id : null;+ voice.phase = 'waiting';+ var inp = el('msg-input');+ if(inp){ inp.style.display = ''; inp.value = text; }+ window._doSend();+ // Not sent (no model picked yet): the picker is open, the turn ends here.+ if(!streaming && !agentRunning){ voiceEnd(); return; }+ voiceLine();+ })+ .catch(function(){ if(token === voice.token) voiceTell(VOICE_TEXT.failed); });+ }++ function voiceDown(){+ if(!voiceSecure()){ voiceTell(VOICE_TEXT.insecure); return; }+ if(voice.phase === 'recording' && voice.mode === 'free'){ voiceFinish(voice.token); return; }+ if(voice.phase === 'speaking'){ voiceEnd(); }+ else if(voice.phase !== 'off') return;+ voice.note = '';+ var token = voice.token;+ voice.downAt = Date.now();+ voice.pendingUp = null;+ voice.mode = null;+ voiceCaps().then(function(c){+ if(token !== voice.token) return;+ if(!c || !c.listen){ voiceTell((c && c.why) || VOICE_TEXT.failed); return; }+ return voiceStartTake(token).then(function(ok){+ if(ok && token === voice.token && voice.pendingUp) voiceDecide(token, voice.pendingUp);+ });+ }, function(){ if(token === voice.token) voiceTell(VOICE_TEXT.failed); });+ }++ function voiceDecide(token, kind){+ voice.pendingUp = null;+ if(kind === 'hold'){ voice.mode = 'hold'; voiceFinish(token); }+ else voiceListenFree(token);+ }++ function voiceUp(){+ if(voice.mode === 'free') return;+ var kind = Date.now() - voice.downAt >= VOICE_HOLD_MS ? 'hold' : 'tap';+ if(!voice.rec){ voice.pendingUp = kind; return; }+ voiceDecide(voice.token, kind);+ }++ function voiceInterrupt(){+ var free = voice.mode === 'free';+ voice.token++;+ try{ if(window.speechSynthesis) window.speechSynthesis.cancel(); }catch(_){}+ if(voice.audio){ try{ voice.audio.pause(); }catch(_){} voice.audio = null; }+ if(free){ voice.mode = 'free'; voiceListenAgain(voice.token); }+ else voiceEnd();+ }++ function voiceLastAnswer(){+ for(var i = msgs.length - 1; i >= 0; i--){ if(msgs[i].role === 'assistant' && !msgs[i].hidden) return msgs[i]; }+ return null;+ }++ /** What of an answer is read aloud: no code, no links, no Markdown marks. */+ function voiceWords(md){+ return String(md || '')+ .replace(/<think>[\s\S]*?<\/think>/gi,' ')+ .replace(/```[\s\S]*?(```|$)/g,' ')+ .replace(/`([^`]+)`/g,'$1')+ .replace(/!\[[^\]]*\]\([^)]*\)/g,' ')+ .replace(/\[([^\]]+)\]\([^)]*\)/g,'$1')+ .replace(/https?:\/\/\S+/g,' ')+ .replace(/^\s{0,3}#{1,6}\s+/gm,'')+ .replace(/^\s*[-*+]\s+/gm,'')+ .replace(/^\s*>\s?/gm,'')+ .replace(/(\*\*|__|\*|_|~~)(?=\S)([\s\S]*?\S)\1/g,'$2')+ .replace(/\|/g,' ')+ .replace(/\s+/g,' ')+ .trim();+ }++ function voiceAfter(token){+ if(token !== voice.token) return;+ if(voice.mode === 'free') voiceListenAgain(token);+ else voiceEnd();+ }++ function voiceSpeakPhone(words){+ return new Promise(function(resolve, reject){+ var u = new SpeechSynthesisUtterance(words);+ var de = (words.match(/[äöüß]|\b(der|die|das|und|ist|nicht|ich|ein|eine|mit)\b/gi) || []).length;+ var en = (words.match(/\b(the|and|is|are|of|to|in|that|it|you)\b/gi) || []).length;+ u.lang = de > en && de >= 2 ? 'de-DE' : en > de && en >= 2 ? 'en-US' : (navigator.language || 'en-US');+ u.onend = function(){ resolve(); };+ u.onerror = function(e){ if(e && (e.error === 'interrupted' || e.error === 'canceled')) resolve(); else reject(e); };+ window.speechSynthesis.speak(u);+ });+ }++ function voiceSpeakComputer(words, token){+ var pieces = [], rest = words, max = (voice.caps && voice.caps.max_speak_chars) || 1500;+ while(rest.length > max){+ var cut = Math.max(rest.lastIndexOf('. ', max), rest.lastIndexOf('? ', max), rest.lastIndexOf('! ', max));+ if(cut < max/3) cut = rest.lastIndexOf(' ', max);+ if(cut < max/3) cut = max;+ pieces.push(rest.slice(0, cut+1).trim()); rest = rest.slice(cut+1).trim();+ }+ if(rest) pieces.push(rest);+ var fetchPiece = function(p){+ return fetch('/remote-api/voice/speak',{method:'POST',headers:{'Authorization':'Bearer '+TOKEN,'Content-Type':'application/json'},body:JSON.stringify({text:p})})+ .then(absorbRefresh)+ .then(function(r){ if(!r.ok) throw new Error('speak '+r.status); return r.blob(); });+ };+ var i = 0;+ var next = pieces.length ? fetchPiece(pieces[0]) : null;+ var play = function(){+ if(!next || token !== voice.token) return Promise.resolve();+ return next.then(function(blob){+ if(token !== voice.token) return;+ i++;+ next = i < pieces.length ? fetchPiece(pieces[i]) : null;+ return new Promise(function(resolve, reject){+ var url = URL.createObjectURL(blob);+ var a = new Audio(url);+ voice.audio = a;+ a.onended = function(){ URL.revokeObjectURL(url); resolve(); };+ a.onerror = function(){ URL.revokeObjectURL(url); reject(new Error('play')); };+ a.play().catch(reject);+ }).then(play);+ });+ };+ return play();+ }++ function voiceHasPhoneVoice(){+ try{ return !!(window.speechSynthesis && window.speechSynthesis.getVoices().length); }catch(_){ return false; }+ }++ /** The chat finished an answer (finishStream, finishToolLoop). */+ function voiceAnswerDone(){+ if(voice.phase !== 'waiting') return;+ var token = voice.token;+ var last = voiceLastAnswer();+ var words = last && last.id !== voice.answerBefore ? voiceWords(last.content) : '';+ if(!words) return voiceAfter(token);+ voice.phase = 'speaking';+ voiceSlot(); voiceLine();+ var spoken = voiceHasPhoneVoice() ? voiceSpeakPhone(words) :+ voiceCaps().then(function(c){ if(!c || !c.speak) return; return voiceSpeakComputer(words, token); });+ spoken.then(function(){ voiceAfter(token); }, function(){+ if(token !== voice.token) return;+ voiceTell(VOICE_TEXT.speakFailed);+ });+ }+})();diff --git a/mobile-client/index.html b/mobile-client/index.htmlindex ea3d14f4..69a88597 100644--- a/mobile-client/index.html+++ b/mobile-client/index.html@@ -12,7 +12,7 @@<!-- Bug #6: restrictive CSP. Self origin only. Inline styles/scripts arerequired because the whole page is a single Rust string; data: imagescover base64 thumbnails; we also need base64 for the QR code JS. -->-<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'">+<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'"><style>/*@@LU_STYLES@@*/</style>diff --git a/mobile-client/styles.css b/mobile-client/styles.cssindex 63a0a4fa..d7dcd8bc 100644--- a/mobile-client/styles.css+++ b/mobile-client/styles.css@@ -344,3 +344,18 @@ button{-webkit-appearance:none;appearance:none}.settings-btn.perm-gap{border-color:var(--accent);color:var(--accent)}.settings-btn.perm-gap::before{content:'';display:inline-block;width:6px;height:6px;border-radius:50%;background:var(--accent);margin-right:6px;animation:perm-pulse 1.4s ease-in-out infinite}@keyframes perm-pulse{0%,100%{opacity:0.4}50%{opacity:1}}+/* Voice over remote (#212): the microphone in the send slot, the line in place of the field. */+.send-btn.mic{background:var(--container);color:var(--text-primary);touch-action:none;-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}+.send-btn.mic.live{background:rgba(239,68,68,0.18);color:#fca5a5}+.voice-line{flex:1;min-height:44px;display:flex;align-items:center;gap:10px;padding:0 4px 0 12px;background:var(--container);border-radius:var(--radius-md);color:var(--text-primary);font-size:0.86rem;min-width:0}+.voice-bars{display:inline-flex;align-items:center;gap:3px;height:20px;flex:none}+.voice-bars i{width:3px;height:100%;border-radius:2px;background:#ef4444;transform:scaleY(0.15);transform-origin:center;transition:transform 90ms linear}+.voice-clock{font-variant-numeric:tabular-nums;color:var(--text-secondary);flex:none}+.voice-hint{flex:1;min-width:0;color:var(--text-secondary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.voice-note{white-space:normal;padding:8px 0;color:var(--text-primary)}+.voice-sub{color:var(--text-tertiary);font-size:0.78rem;white-space:nowrap}+.voice-tap{flex:1;min-width:0;min-height:44px;display:flex;align-items:center;gap:8px;background:none;border:none;color:inherit;font:inherit;text-align:left;padding:0}+.voice-end{flex:none;min-width:44px;min-height:44px;background:none;border:none;color:var(--text-primary);font:inherit;font-weight:600;padding:0 8px;cursor:pointer}+.voice-spin{width:16px;height:16px;border-radius:50%;border:2px solid var(--text-tertiary);border-top-color:transparent;animation:voice-spin 0.8s linear infinite;flex:none}+@keyframes voice-spin{to{transform:rotate(360deg)}}+@media (prefers-reduced-motion: reduce){.voice-bars i{transition:none}.voice-spin{animation:none}}diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 35864880..61883b11 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -86,6 +86,7 @@ pub mod lan_address;pub mod remote;pub mod remote_chats;pub mod remote_create;+pub mod remote_voice;pub mod video_thumb;// Colour settle across the seams of a long video, on ComfyUI's Python.// Desktop only: it starts a process.diff --git a/src-tauri/src/commands/remote.rs b/src-tauri/src/commands/remote.rsindex 45cf9843..a705e5d1 100644--- a/src-tauri/src/commands/remote.rs+++ b/src-tauri/src/commands/remote.rs@@ -258,6 +258,12 @@ impl axum::extract::FromRef<RemoteState> for crate::commands::remote_chats::Chat}}+impl axum::extract::FromRef<RemoteState> for crate::commands::remote_voice::VoiceCtx {+ fn from_ref(state: &RemoteState) -> Self {+ crate::commands::remote_voice::VoiceCtx::of_desktop(state.app_handle.handle())+ }+}+impl axum::extract::FromRef<RemoteState> for crate::commands::remote_create::CreateCtx {fn from_ref(state: &RemoteState) -> Self {crate::commands::remote_create::CreateCtx {@@ -789,6 +795,11 @@ async fn handle_status_full(if sealed_caller.as_ref().is_some_and(|c| c.rights.chat) {features.extend(state.chats.features());}+ // Voice over remote (#212): wherever the caller may chat. Whether this+ // computer can listen right now says `/remote-api/voice` itself.+ if sealed_caller.as_ref().is_none_or(|c| c.rights.chat) {+ features.push(crate::commands::remote_voice::FEATURE.to_string());+ }let devices = state.connected_devices.lock().await;let mut body = status_full_body(&devices, &machine_name(), &features);// Inside the channel only: the Windows Firewall drops the Wi-Fi way, so a@@ -4623,7 +4634,16 @@ fn build_router(state: RemoteState) -> Router {.route("/remote-api/chats/{id}/stop", post(crate::commands::remote_chats::handle_stop)).route("/remote-api/chats/{id}/read", post(crate::commands::remote_chats::handle_read)).route("/remote-api/approvals/{id}", post(crate::commands::remote_chats::handle_approval))- .route("/remote-api/tasks", get(crate::commands::remote_chats::handle_tasks));+ .route("/remote-api/tasks", get(crate::commands::remote_chats::handle_tasks))+ // Voice over remote (remote_voice.rs, GitHub #212): with the right `chat`,+ // on the Wi-Fi way with a JWT and inside the sealed channel.+ .route(crate::commands::remote_voice::STATUS_PATH, get(crate::commands::remote_voice::handle_status))+ .route(+ crate::commands::remote_voice::TRANSCRIBE_PATH,+ post(crate::commands::remote_voice::handle_transcribe)+ .layer(axum::extract::DefaultBodyLimit::max(crate::commands::remote_voice::MAX_TAKE_BYTES + 1)),+ )+ .route(crate::commands::remote_voice::SPEAK_PATH, post(crate::commands::remote_voice::handle_speak));// Proxy routeslet proxy_routes = Router::new()@@ -5453,7 +5473,8 @@ mod remote_path_tests {let v: serde_json::Value = tool.json().await.unwrap();assert!(v["error"].is_string());let status: serde_json::Value = c.get(format!("{base}/remote-api/status/full")).bearer_auth(&token).send().await.unwrap().json().await.unwrap();- assert_eq!(status["features"], serde_json::json!([]));+ // Voice over remote (#212) is offered wherever the caller may chat.+ assert_eq!(status["features"], serde_json::json!(["voice"]));server.permissions.lock().await.create = true;let accepted = c.post(&url).bearer_auth(&token).json(&job).send().await.unwrap();@@ -5461,7 +5482,7 @@ mod remote_path_tests {let v: serde_json::Value = accepted.json().await.unwrap();assert_eq!(v["state"], "running");let status: serde_json::Value = c.get(format!("{base}/remote-api/status/full")).bearer_auth(&token).send().await.unwrap().json().await.unwrap();- assert_eq!(status["features"], serde_json::json!(["create-image", "create-video"]));+ assert_eq!(status["features"], serde_json::json!(["create-image", "create-video", "voice"]));assert!(status.get("lan_blocked").is_none(), "only inside the channel");// Stage 2, the gallery and documents stay in the sealed channel: the// plain Wi-Fi way keeps 3.0.7's Create.diff --git a/src-tauri/src/commands/remote_sealed.rs b/src-tauri/src/commands/remote_sealed.rsindex 6337aa88..a486f91e 100644--- a/src-tauri/src/commands/remote_sealed.rs+++ b/src-tauri/src/commands/remote_sealed.rs@@ -187,6 +187,8 @@ pub(crate) fn right_for_path(path: &str) -> Option<&'static str> {|| path.starts_with("/remote-api/chats/")|| path.starts_with("/remote-api/approvals/")|| path == "/remote-api/tasks"+ || path == crate::commands::remote_voice::STATUS_PATH+ || path.starts_with("/remote-api/voice/"){Some("chat")} else if path == "/remote-api/agent-tool" {diff --git a/src-tauri/src/commands/remote_sealed/tests.rs b/src-tauri/src/commands/remote_sealed/tests.rsindex bffee5a9..80012b6f 100644--- a/src-tauri/src/commands/remote_sealed/tests.rs+++ b/src-tauri/src/commands/remote_sealed/tests.rs@@ -851,10 +851,10 @@ async fn create_runs_end_to_end_through_the_sealed_channel() {// Without its own right the status names no Create, with it it does.let status = phone.call(&c.rig, via, "GET", "/remote-api/status/full", b"").await.unwrap();- assert_eq!(status.json()["features"], serde_json::json!(["sealed", "pending", "signin"]));+ assert_eq!(status.json()["features"], serde_json::json!(["sealed", "pending", "signin", "voice"]));c.allow_create(&phone);let status = phone.call(&c.rig, via, "GET", "/remote-api/status/full", b"").await.unwrap();- assert_eq!(status.json()["features"], serde_json::json!(["sealed", "pending", "signin", "create-image", "create-video"]));+ assert_eq!(status.json()["features"], serde_json::json!(["sealed", "pending", "signin", "create-image", "create-video", "voice"]));// The unauthenticated tunnel status stays without Create.let (_, _, body) = send(&c.rig, via, "GET", "/remote-api/status", Vec::new()).await;let v: serde_json::Value = serde_json::from_slice(&body).unwrap();@@ -868,7 +868,7 @@ async fn create_runs_end_to_end_through_the_sealed_channel() {// Stage 2 (CREATE-V2.md): once the window answered, the gallery word;// a kind's word only where the engine can (here none).let status = phone.call(&c.rig, via, "GET", "/remote-api/status/full", b"").await.unwrap();- assert_eq!(status.json()["features"], serde_json::json!(["sealed", "pending", "signin", "create-image", "create-video", "create-gallery"]));+ assert_eq!(status.json()["features"], serde_json::json!(["sealed", "pending", "signin", "create-image", "create-video", "create-gallery", "voice"]));let unavailable = phone.call(&c.rig, via, "POST", "/remote-api/create/jobs", &job_body("music", "lofi")).await.unwrap();assert_eq!(unavailable.status, 409, "{:?}", unavailable.json());@@ -1965,6 +1965,33 @@ async fn shared_chats_go_through_the_channel_with_the_right_chat() {assert_eq!(tasks.status, 403);}+// ── Voice over remote (#212) ──++#[tokio::test]+async fn voice_goes_through_the_channel_with_the_right_chat() {+ let rig = rig_with(Duration::from_secs(5), Duration::from_secs(5)).await;+ let via = Via::Tunnel("198.51.100.93");+ let phone = paired_phone(&rig, 0x53, via).await;+ // The test server has no desktop behind it: the status says so, a take is answered 503 with the reason.+ let status = phone.call(&rig, via, "GET", "/remote-api/voice", b"").await.unwrap();+ assert_eq!(status.status, 200, "{:?}", status.json());+ assert_eq!(status.json()["listen"], false);+ assert!(status.json()["why"].as_str().unwrap().contains("desktop app"));+ let mut wav = b"RIFF\0\0\0\0WAVEfmt ".to_vec();+ wav.resize(4000, 0);+ let take = phone.call(&rig, via, "POST", "/remote-api/voice/transcribe", &wav).await.unwrap();+ assert_eq!(take.status, 503, "{:?}", take.json());+ // Without the right chat: the channel's 403 before any handler.+ rig.hub.set_rights(&phone.device_id(), DeviceRights { agent: true, ..DeviceRights::default() }).unwrap();+ for path in ["/remote-api/voice", "/remote-api/voice/transcribe", "/remote-api/voice/speak"] {+ let method = if path == "/remote-api/voice" { "GET" } else { "POST" };+ let refused = phone.call(&rig, via, method, path, b"{}").await.unwrap();+ assert_eq!((refused.status, refused.json()["right"].clone()), (403, serde_json::json!("chat")), "{path}");+ }+ let status = phone.call(&rig, via, "GET", "/remote-api/status/full", b"").await.unwrap();+ assert!(!status.json()["features"].as_array().unwrap().contains(&serde_json::json!("voice")));+}+// ── Chat attachments with the right `chat` alone ──#[tokio::test]diff --git a/src-tauri/src/commands/remote_voice.rs b/src-tauri/src/commands/remote_voice.rsnew file mode 100644index 00000000..af65303a--- /dev/null+++ b/src-tauri/src/commands/remote_voice.rs@@ -0,0 +1,480 @@+//! Voice over Remote (GitHub #212): a phone talks to LU on this computer and+//! hears the answer.+//!+//! The phone records one take at a time (push to talk, or hands free where+//! the phone itself hears the end of a sentence), sends it here, and this+//! computer writes it down with the speech recognition it already has for+//! dictation (faster-whisper, `whisper.rs`). The text then goes into the chat+//! like a typed message. For the answer the phone uses its own voice first;+//! a phone without one asks this computer to speak it with Piper (`tts.rs`).+//!+//! Turns, not a live audio stream: the remote way is one sealed request after+//! the other, also through the tunnel, and a take of a few seconds fits in+//! one of them. Nothing of the take is kept: whisper.rs writes it to a private+//! temporary folder and removes it after the transcription.+//!+//! Routes, behind `auth_middleware` and the device right `chat`+//! (`remote_sealed::right_for_path`), on the LAN listener with a JWT and+//! inside the sealed channel:+//!+//! * `GET /remote-api/voice` what this computer can do right now+//! * `POST /remote-api/voice/transcribe` a WAV take, answers `{ "text" }`+//! * `POST /remote-api/voice/speak` `{ "text" }`, answers a WAV++use std::future::Future;+use std::pin::Pin;+use std::sync::{Arc, Mutex};+use std::time::{Duration, Instant};++use axum::{+ body::Bytes,+ extract::{rejection::JsonRejection, State as AxumState},+ http::{header, HeaderMap, StatusCode},+ response::{IntoResponse, Response},+ Json,+};+use serde::Deserialize;+use serde_json::{json, Value};++use super::remote::CallerDevice;++pub(crate) const STATUS_PATH: &str = "/remote-api/voice";+pub(crate) const TRANSCRIBE_PATH: &str = "/remote-api/voice/transcribe";+pub(crate) const SPEAK_PATH: &str = "/remote-api/voice/speak";++/// The feature word in the authenticated status.+pub(crate) const FEATURE: &str = "voice";++/// A take, as WAV. Two minutes of 16 kHz mono 16 bit are 3.84 MB; a sealed+/// message holds 8 MiB, base64 included.+pub(crate) const MAX_TAKE_BYTES: usize = 4 * 1024 * 1024;+/// The longest take the phone records, told to it in the status.+pub(crate) const MAX_TAKE_MS: u64 = 120_000;+/// One piece of an answer to speak. The phone sends a sentence or a few.+pub(crate) const MAX_SPEAK_CHARS: usize = 1500;++// A take fits into one sealed message: base64 grows by a third, and the+// request around it needs room too.+const _: () = assert!(MAX_TAKE_BYTES * 4 / 3 + 64 * 1024 < crate::remote_seal::MAX_MESSAGE);+/// What the status said is kept this long: each answer of it starts Python twice.+const STATUS_KEEP: Duration = Duration::from_secs(20);++pub(crate) type EngineFuture<T> = Pin<Box<dyn Future<Output = Result<T, String>> + Send>>;++/// What this computer can do for a phone's voice.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(crate) struct Abilities {+ /// Speech recognition is installed (faster-whisper).+ pub listen: bool,+ /// A Piper voice can speak.+ pub speak: bool,+}++/// The speech work itself. The real one runs the desktop's own engines; the+/// tests put in one of their own.+pub(crate) trait VoiceEngine: Send + Sync {+ fn abilities(&self) -> EngineFuture<Abilities>;+ /// The text of a take. `Err` carries a sentence for the user.+ fn transcribe(&self, wav: Vec<u8>) -> EngineFuture<String>;+ /// A WAV of `text`.+ fn speak(&self, text: String) -> EngineFuture<Vec<u8>>;+}++/// The status of the engines, and when it was asked.+type Kept = Arc<Mutex<Option<(Instant, Abilities)>>>;++/// What the voice routes need from the server state.+#[derive(Clone)]+pub(crate) struct VoiceCtx {+ pub engine: Option<Arc<dyn VoiceEngine>>,+ status: Kept,+}++impl VoiceCtx {+ #[cfg(test)]+ pub(crate) fn new(engine: Option<Arc<dyn VoiceEngine>>) -> Self {+ Self { engine, status: Arc::new(Mutex::new(None)) }+ }++ /// The context of the running server: the desktop's engines, and one kept+ /// status for the whole process (the server builds this per request).+ pub(crate) fn of_desktop(app: Option<&tauri::AppHandle>) -> Self {+ static KEPT: std::sync::OnceLock<Kept> = std::sync::OnceLock::new();+ let engine: Option<Arc<dyn VoiceEngine>> = app.map(|a| Arc::new(DesktopVoice::new(a.clone())) as Arc<dyn VoiceEngine>);+ Self { engine, status: KEPT.get_or_init(|| Arc::new(Mutex::new(None))).clone() }+ }++ async fn abilities(&self) -> Abilities {+ let Some(engine) = &self.engine else {+ return Abilities { listen: false, speak: false };+ };+ if let Some((at, kept)) = *self.status.lock().unwrap() {+ if at.elapsed() < STATUS_KEEP {+ return kept;+ }+ }+ let found = engine.abilities().await.unwrap_or(Abilities { listen: false, speak: false });+ *self.status.lock().unwrap() = Some((Instant::now(), found));+ found+ }++ /// Forget the kept status: after a failed take the next status asks again.+ fn forget(&self) {+ *self.status.lock().unwrap() = None;+ }+}++const NO_LISTEN: &str = "Speech recognition is not set up on the computer. In LU on the computer open Settings, Voice & Remote, and install speech to text, or set up Voice.";+const NO_SPEAK: &str = "The computer has no voice set up for reading aloud.";+const NOT_HERE: &str = "Voice over remote needs the LU desktop app on the computer.";++fn said(status: StatusCode, error: &str, message: &str) -> Response {+ (status, Json(json!({ "error": error, "message": message }))).into_response()+}++/// The status body. `why` names the one thing a phone can tell its user.+pub(crate) fn status_body(a: Abilities, here: bool) -> Value {+ let why = if !here {+ Some(NOT_HERE)+ } else if !a.listen {+ Some(NO_LISTEN)+ } else {+ None+ };+ json!({+ "listen": a.listen,+ "speak": a.speak,+ "max_take_bytes": MAX_TAKE_BYTES,+ "max_take_ms": MAX_TAKE_MS,+ "max_speak_chars": MAX_SPEAK_CHARS,+ "why": why,+ })+}++fn has_caller(caller: &Option<axum::Extension<CallerDevice>>) -> bool {+ caller.is_some()+}++pub(crate) async fn handle_status(AxumState(ctx): AxumState<VoiceCtx>, caller: Option<axum::Extension<CallerDevice>>) -> Response {+ if !has_caller(&caller) {+ return StatusCode::UNAUTHORIZED.into_response();+ }+ let here = ctx.engine.is_some();+ Json(status_body(ctx.abilities().await, here)).into_response()+}++/// A RIFF/WAVE header, nothing more: the decoder on the other side checks the rest.+pub(crate) fn looks_like_wav(body: &[u8]) -> bool {+ body.len() > 44 && &body[0..4] == b"RIFF" && &body[8..12] == b"WAVE"+}++pub(crate) async fn handle_transcribe(+ AxumState(ctx): AxumState<VoiceCtx>,+ caller: Option<axum::Extension<CallerDevice>>,+ headers: HeaderMap,+ body: Bytes,+) -> Response {+ if !has_caller(&caller) {+ return StatusCode::UNAUTHORIZED.into_response();+ }+ let Some(engine) = ctx.engine.clone() else {+ return said(StatusCode::SERVICE_UNAVAILABLE, "unavailable", NOT_HERE);+ };+ if body.len() > MAX_TAKE_BYTES {+ return said(StatusCode::PAYLOAD_TOO_LARGE, "too_long", "The recording is too long. Keep a message under two minutes.");+ }+ let declared = headers.get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("");+ if !declared.is_empty() && !declared.starts_with("audio/wav") && !declared.starts_with("audio/x-wav") && !declared.starts_with("application/octet-stream") {+ return said(StatusCode::UNSUPPORTED_MEDIA_TYPE, "not_wav", "The recording has to be a WAV file.");+ }+ if !looks_like_wav(&body) {+ return said(StatusCode::BAD_REQUEST, "not_wav", "The recording is empty or not a WAV file.");+ }+ if !ctx.abilities().await.listen {+ return said(StatusCode::CONFLICT, "no_listen", NO_LISTEN);+ }+ match engine.transcribe(body.to_vec()).await {+ Ok(text) => Json(json!({ "text": text.trim() })).into_response(),+ Err(why) => {+ ctx.forget();+ said(StatusCode::BAD_GATEWAY, "failed", &why)+ }+ }+}++#[derive(Deserialize)]+pub(crate) struct SpeakBody {+ text: String,+}++pub(crate) async fn handle_speak(+ AxumState(ctx): AxumState<VoiceCtx>,+ caller: Option<axum::Extension<CallerDevice>>,+ body: Result<Json<SpeakBody>, JsonRejection>,+) -> Response {+ if !has_caller(&caller) {+ return StatusCode::UNAUTHORIZED.into_response();+ }+ let Some(engine) = ctx.engine.clone() else {+ return said(StatusCode::SERVICE_UNAVAILABLE, "unavailable", NOT_HERE);+ };+ let Ok(Json(body)) = body else {+ return said(StatusCode::BAD_REQUEST, "bad_request", "Send the text as JSON: { \"text\": \"…\" }.");+ };+ let text = body.text.trim().to_string();+ if text.is_empty() {+ return said(StatusCode::BAD_REQUEST, "empty", "There is nothing to read aloud.");+ }+ if text.chars().count() > MAX_SPEAK_CHARS {+ return said(StatusCode::PAYLOAD_TOO_LARGE, "too_long", "Send the answer in shorter pieces.");+ }+ if !ctx.abilities().await.speak {+ return said(StatusCode::CONFLICT, "no_speak", NO_SPEAK);+ }+ match engine.speak(text).await {+ Ok(wav) => ([(header::CONTENT_TYPE, "audio/wav"), (header::CACHE_CONTROL, "no-store")], wav).into_response(),+ Err(why) => {+ ctx.forget();+ said(StatusCode::BAD_GATEWAY, "failed", &why)+ }+ }+}++/// The engines of this desktop: faster-whisper for the take, Piper for the answer.+pub(crate) struct DesktopVoice {+ app: tauri::AppHandle,+}++impl DesktopVoice {+ pub(crate) fn new(app: tauri::AppHandle) -> Self {+ Self { app }+ }+}++/// The Piper voice to speak in: the default when it is complete, else the first complete one.+fn pick_voice(installed: &[String]) -> Option<String> {+ let default = super::tts::PIPER_VOICE.to_string();+ if installed.contains(&default) {+ return Some(default);+ }+ installed.first().cloned()+}++impl VoiceEngine for DesktopVoice {+ fn abilities(&self) -> EngineFuture<Abilities> {+ let app = self.app.clone();+ Box::pin(async move {+ let listen = super::whisper::whisper_status(app.clone())+ .await+ .ok()+ .and_then(|v| v.get("available").and_then(Value::as_bool))+ .unwrap_or(false);+ let speak = tokio::task::spawn_blocking(move || {+ use tauri::Manager;+ let state = app.state::<crate::state::AppState>();+ super::tts::tts_status(None, state, app.clone())+ .ok()+ .and_then(|v| v.get("available").and_then(Value::as_bool))+ .unwrap_or(false)+ })+ .await+ .unwrap_or(false);+ Ok(Abilities { listen, speak })+ })+ }++ fn transcribe(&self, wav: Vec<u8>) -> EngineFuture<String> {+ let app = self.app.clone();+ Box::pin(async move {+ let b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &wav);+ let answer = super::whisper::transcribe(app, b64, "audio/wav".to_string()).await?;+ if let Some(error) = answer.get("error").and_then(Value::as_str) {+ return Err(error.to_string());+ }+ Ok(answer.get("transcript").and_then(Value::as_str).unwrap_or("").to_string())+ })+ }++ fn speak(&self, text: String) -> EngineFuture<Vec<u8>> {+ let app = self.app.clone();+ Box::pin(async move {+ let installed = super::tts::installed_piper_voices(app.clone()).unwrap_or_default();+ let Some(voice) = pick_voice(&installed) else {+ return Err(NO_SPEAK.to_string());+ };+ let answer = super::tts::synthesize(text, Some(voice), app).await?;+ let b64 = answer.get("audio_base64").and_then(Value::as_str).ok_or("The computer made no sound.")?;+ base64::Engine::decode(&base64::engine::general_purpose::STANDARD, b64).map_err(|_| "The computer made no sound.".to_string())+ })+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use axum::{body::Body, http::Request, routing::{get, post}, Router};+ use std::sync::atomic::{AtomicUsize, Ordering};+ use tower::ServiceExt;++ struct Fake {+ abilities: Abilities,+ asked: AtomicUsize,+ heard: Mutex<Vec<usize>>,+ }++ impl VoiceEngine for Fake {+ fn abilities(&self) -> EngineFuture<Abilities> {+ self.asked.fetch_add(1, Ordering::SeqCst);+ let a = self.abilities;+ Box::pin(async move { Ok(a) })+ }+ fn transcribe(&self, wav: Vec<u8>) -> EngineFuture<String> {+ self.heard.lock().unwrap().push(wav.len());+ Box::pin(async { Ok(" hello computer ".to_string()) })+ }+ fn speak(&self, text: String) -> EngineFuture<Vec<u8>> {+ Box::pin(async move { Ok(format!("RIFF....WAVE{text}").into_bytes()) })+ }+ }++ fn fake(listen: bool, speak: bool) -> Arc<Fake> {+ Arc::new(Fake { abilities: Abilities { listen, speak }, asked: AtomicUsize::new(0), heard: Mutex::new(vec![]) })+ }++ fn router(engine: Option<Arc<dyn VoiceEngine>>, signed_in: bool) -> Router {+ let ctx = VoiceCtx::new(engine);+ let r = Router::new()+ .route(STATUS_PATH, get(handle_status))+ // As in remote.rs: the take may be larger than axum's default limit.+ .route(TRANSCRIBE_PATH, post(handle_transcribe).layer(axum::extract::DefaultBodyLimit::max(MAX_TAKE_BYTES + 1)))+ .route(SPEAK_PATH, post(handle_speak))+ .with_state(ctx);+ if signed_in {+ r.layer(axum::middleware::from_fn(|mut req: axum::extract::Request, next: axum::middleware::Next| async move {+ req.extensions_mut().insert(CallerDevice("phone-1".to_string()));+ next.run(req).await+ }))+ } else {+ r+ }+ }++ fn wav(len: usize) -> Vec<u8> {+ let mut v = b"RIFF\0\0\0\0WAVEfmt ".to_vec();+ v.resize(len, 0);+ v+ }++ async fn call(r: Router, method: &str, path: &str, ct: &str, body: Vec<u8>) -> (StatusCode, Vec<u8>) {+ let req = Request::builder().method(method).uri(path).header("content-type", ct).body(Body::from(body)).unwrap();+ let res = r.oneshot(req).await.unwrap();+ let status = res.status();+ let bytes = axum::body::to_bytes(res.into_body(), usize::MAX).await.unwrap().to_vec();+ (status, bytes)+ }++ fn json_of(b: &[u8]) -> Value {+ serde_json::from_slice(b).unwrap()+ }++ #[tokio::test]+ async fn every_route_wants_a_known_device() {+ for (m, p) in [("GET", STATUS_PATH), ("POST", TRANSCRIBE_PATH), ("POST", SPEAK_PATH)] {+ let (s, _) = call(router(Some(fake(true, true)), false), m, p, "audio/wav", wav(100)).await;+ assert_eq!(s, StatusCode::UNAUTHORIZED, "{p}");+ }+ }++ #[tokio::test]+ async fn the_status_says_what_the_computer_can_and_why_not() {+ let (s, b) = call(router(Some(fake(true, false)), true), "GET", STATUS_PATH, "", vec![]).await;+ assert_eq!(s, StatusCode::OK);+ let v = json_of(&b);+ assert_eq!(v["listen"], true);+ assert_eq!(v["speak"], false);+ assert_eq!(v["max_take_bytes"], MAX_TAKE_BYTES);+ assert!(v["why"].is_null());++ let v = json_of(&call(router(Some(fake(false, true)), true), "GET", STATUS_PATH, "", vec![]).await.1);+ assert_eq!(v["listen"], false);+ assert!(v["why"].as_str().unwrap().contains("Settings, Voice & Remote"));++ let v = json_of(&call(router(None, true), "GET", STATUS_PATH, "", vec![]).await.1);+ assert_eq!(v["listen"], false);+ assert_eq!(v["why"], NOT_HERE);+ }++ #[tokio::test]+ async fn the_status_is_kept_a_little_while() {+ let engine = fake(true, true);+ let ctx = VoiceCtx::new(Some(engine.clone()));+ ctx.abilities().await;+ ctx.abilities().await;+ assert_eq!(engine.asked.load(Ordering::SeqCst), 1);+ ctx.forget();+ ctx.abilities().await;+ assert_eq!(engine.asked.load(Ordering::SeqCst), 2);+ }++ #[tokio::test]+ async fn a_take_comes_back_as_trimmed_text() {+ let engine = fake(true, false);+ let (s, b) = call(router(Some(engine.clone()), true), "POST", TRANSCRIBE_PATH, "audio/wav", wav(3000)).await;+ assert_eq!(s, StatusCode::OK);+ assert_eq!(json_of(&b)["text"], "hello computer");+ assert_eq!(*engine.heard.lock().unwrap(), vec![3000]);+ }++ #[tokio::test]+ async fn a_take_that_is_no_wav_or_too_long_is_refused_before_the_engine() {+ let engine = fake(true, true);+ let (s, _) = call(router(Some(engine.clone()), true), "POST", TRANSCRIBE_PATH, "audio/wav", b"hello".to_vec()).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let (s, _) = call(router(Some(engine.clone()), true), "POST", TRANSCRIBE_PATH, "audio/webm", wav(3000)).await;+ assert_eq!(s, StatusCode::UNSUPPORTED_MEDIA_TYPE);+ let (s, b) = call(router(Some(engine.clone()), true), "POST", TRANSCRIBE_PATH, "audio/wav", wav(MAX_TAKE_BYTES + 1)).await;+ assert_eq!(s, StatusCode::PAYLOAD_TOO_LARGE);+ assert_eq!(json_of(&b)["error"], "too_long");+ assert!(engine.heard.lock().unwrap().is_empty());+ }++ #[tokio::test]+ async fn without_speech_recognition_the_take_gets_the_reason() {+ let (s, b) = call(router(Some(fake(false, true)), true), "POST", TRANSCRIBE_PATH, "audio/wav", wav(3000)).await;+ assert_eq!(s, StatusCode::CONFLICT);+ assert_eq!(json_of(&b)["error"], "no_listen");+ }++ #[tokio::test]+ async fn speak_answers_a_wav_and_refuses_what_it_cannot() {+ let ok = call(router(Some(fake(true, true)), true), "POST", SPEAK_PATH, "application/json", br#"{"text":" Hi there. "}"#.to_vec()).await;+ assert_eq!(ok.0, StatusCode::OK);+ assert_eq!(ok.1, b"RIFF....WAVEHi there.".to_vec());++ let none = call(router(Some(fake(true, false)), true), "POST", SPEAK_PATH, "application/json", br#"{"text":"Hi"}"#.to_vec()).await;+ assert_eq!(none.0, StatusCode::CONFLICT);+ assert_eq!(json_of(&none.1)["error"], "no_speak");++ let empty = call(router(Some(fake(true, true)), true), "POST", SPEAK_PATH, "application/json", br#"{"text":" "}"#.to_vec()).await;+ assert_eq!(empty.0, StatusCode::BAD_REQUEST);++ let long = json!({ "text": "a".repeat(MAX_SPEAK_CHARS + 1) }).to_string().into_bytes();+ let long = call(router(Some(fake(true, true)), true), "POST", SPEAK_PATH, "application/json", long).await;+ assert_eq!(long.0, StatusCode::PAYLOAD_TOO_LARGE);+ }++ #[test]+ fn the_default_voice_comes_first() {+ assert_eq!(pick_voice(&[]), None);+ assert_eq!(pick_voice(&["de_DE-thorsten-medium".into()]), Some("de_DE-thorsten-medium".into()));+ assert_eq!(pick_voice(&["de_DE-thorsten-medium".into(), super::super::tts::PIPER_VOICE.into()]), Some(super::super::tts::PIPER_VOICE.into()));+ }++ #[test]+ fn the_routes_need_the_right_chat() {+ use super::super::remote_sealed::right_for_path;+ for path in [STATUS_PATH, TRANSCRIBE_PATH, SPEAK_PATH] {+ assert_eq!(right_for_path(path), Some("chat"), "{path}");+ }+ }+}diff --git a/src/mobile/remote/__tests__/remoteVoice.test.ts b/src/mobile/remote/__tests__/remoteVoice.test.tsnew file mode 100644index 00000000..9aa6980f--- /dev/null+++ b/src/mobile/remote/__tests__/remoteVoice.test.ts@@ -0,0 +1,159 @@+/**+ * Voice over remote (GitHub #212): the pure parts of remote/remoteVoice.ts and+ * that the page in the phone's browser (mobile-client/client.js) keeps to the+ * same numbers and the same routes.+ *+ * Run: npx vitest run src/mobile/remote/__tests__/remoteVoice.test.ts+ */+import { readFileSync } from 'node:fs'+import { join } from 'node:path'+import { describe, expect, it } from 'vitest'+import {+ END_QUIET_MS,+ GIVE_UP_MS,+ HOLD_MS,+ MIN_TAKE_MS,+ nextTurn,+ pressKind,+ QUIET_LEVEL,+ readComputerVoice,+ SPEECH_LEVEL,+ SPEECH_MIN_MS,+ speakableText,+ speechPieces,+ startTurn,+ voiceErrorOf,+ VOICE_PATHS,+ type TurnState,+} from '../remoteVoice'++const ROOT = join(__dirname, '..', '..', '..', '..')++/** Feed levels every 90 ms like the meter does and collect the events with their time. The caller stops at 'end' or 'give-up', so does this. */+function feed(levels: Array<[number, number]>): Array<[number, string]> {+ let state: TurnState = startTurn(0)+ let t = 0+ const out: Array<[number, string]> = []+ for (const [level, ms] of levels) {+ const until = t + ms+ for (; t < until; t += 90) {+ const step = nextTurn(state, level, t)+ state = step.state+ if (step.event) out.push([t, step.event])+ if (step.event === 'end' || step.event === 'give-up') return out+ }+ }+ return out+}++describe('the status of the computer', () => {+ it('reads what is there and counts anything missing as cannot', () => {+ expect(readComputerVoice({ listen: true, speak: false, max_take_bytes: 1000, max_take_ms: 5000, max_speak_chars: 200, why: null })).toEqual({+ listen: true, speak: false, maxTakeBytes: 1000, maxTakeMs: 5000, maxSpeakChars: 200, why: null,+ })+ const none = readComputerVoice('nonsense')+ expect(none.listen).toBe(false)+ expect(none.speak).toBe(false)+ expect(none.maxSpeakChars).toBe(1500)+ expect(readComputerVoice({ listen: false, why: ' Install speech to text. ' }).why).toBe('Install speech to text.')+ })++ it('turns an answer that is not 2xx into what to tell the user', () => {+ expect(voiceErrorOf(404, null).code).toBe('too-old')+ expect(voiceErrorOf(413, { error: 'too_long', message: 'Too long.' }).message).toBe('Too long.')+ expect(voiceErrorOf(409, { error: 'no_listen', message: 'Set it up.' })).toMatchObject({ code: 'no-listen', message: 'Set it up.' })+ expect(voiceErrorOf(502, { error: 'failed', message: 'Whisper not available' })).toMatchObject({ code: 'failed', message: 'Whisper not available' })+ expect(voiceErrorOf(500, null).code).toBe('protocol')+ })+})++describe('what of an answer is read aloud', () => {+ it('leaves out code, thoughts, links and the marks of Markdown', () => {+ const md = '<think>plan it</think>## Result\n\nThe **answer** is `42`, see [the docs](https://x.y/z).\n\n```js\nconsole.log(1)\n```\n- one\n- two\n> quoted'+ expect(speakableText(md)).toBe('Result The answer is 42, see the docs. one two quoted')+ })++ it('cuts long text after a sentence, never in the middle of a word', () => {+ const text = 'One sentence here. ' + 'Another one that goes on. '.repeat(10)+ const pieces = speechPieces(text, 60)+ expect(pieces.every((p) => p.length <= 60)).toBe(true)+ expect(pieces.join(' ')).toBe(text.trim())+ expect(pieces[0].endsWith('.')).toBe(true)+ expect(speechPieces('short', 60)).toEqual(['short'])+ expect(speechPieces('', 60)).toEqual([])+ })+})++describe('hands free hears the end of a sentence', () => {+ it('a sentence and a pause end the take once', () => {+ const events = feed([[0, 1000], [0.4, 1500], [0.01, 2000]])+ expect(events.map((e) => e[1])).toEqual(['speech', 'end'])+ const [speechAt, endAt] = events.map((e) => e[0])+ expect(speechAt).toBeGreaterThanOrEqual(1000 + SPEECH_MIN_MS)+ expect(endAt - 2500).toBeGreaterThanOrEqual(END_QUIET_MS - 90)+ expect(endAt - 2500).toBeLessThan(END_QUIET_MS + 200)+ })++ it('a click or a cough does not start a take', () => {+ expect(feed([[0.5, 150], [0, 2000]])).toEqual([])+ })++ it('a short breath between words does not end it', () => {+ const events = feed([[0.4, 800], [0.02, 600], [0.4, 800], [0.02, 1500]])+ expect(events.filter((e) => e[1] === 'end')).toHaveLength(1)+ expect(events.find((e) => e[1] === 'end')![0]).toBeGreaterThan(2200)+ })++ it('a fading word between the two levels keeps the take open', () => {+ expect(QUIET_LEVEL).toBeLessThan(SPEECH_LEVEL)+ const events = feed([[0.4, 800], [(QUIET_LEVEL + SPEECH_LEVEL) / 2, 3000]])+ expect(events.map((e) => e[1])).toEqual(['speech'])+ })++ it('a long silence gives up', () => {+ const events = feed([[0, GIVE_UP_MS + 500]])+ expect(events[0][1]).toBe('give-up')+ expect(events[0][0]).toBeGreaterThanOrEqual(GIVE_UP_MS)+ })+})++describe('the press on the microphone', () => {+ it('short is a tap, long is push to talk', () => {+ expect(pressKind(1000, 1000 + HOLD_MS - 1)).toBe('tap')+ expect(pressKind(1000, 1000 + HOLD_MS)).toBe('hold')+ expect(MIN_TAKE_MS).toBeGreaterThan(HOLD_MS)+ })+})++describe('the page in the phone browser keeps to the same', () => {+ const client = readFileSync(join(ROOT, 'mobile-client', 'client.js'), 'utf8')+ const page = readFileSync(join(ROOT, 'mobile-client', 'index.html'), 'utf8')+ const num = (name: string) => Number(client.match(new RegExp(`var ${name} = ([0-9.]+);`))?.[1])++ it('the same levels and times', () => {+ expect(num('VOICE_SPEECH_LEVEL')).toBe(SPEECH_LEVEL)+ expect(num('VOICE_QUIET_LEVEL')).toBe(QUIET_LEVEL)+ expect(num('VOICE_SPEECH_MIN_MS')).toBe(SPEECH_MIN_MS)+ expect(num('VOICE_END_QUIET_MS')).toBe(END_QUIET_MS)+ expect(num('VOICE_GIVE_UP_MS')).toBe(GIVE_UP_MS)+ expect(num('VOICE_HOLD_MS')).toBe(HOLD_MS)+ expect(num('VOICE_MIN_TAKE_MS')).toBe(MIN_TAKE_MS)+ })++ it('the same routes, and the answer is read when the chat or the agent finishes', () => {+ for (const path of Object.values(VOICE_PATHS)) expect(client).toContain(`'${path}'`)+ const finishStream = client.slice(client.indexOf('function finishStream(){'))+ expect(finishStream.slice(0, finishStream.indexOf('\n }'))).toContain('voiceAnswerDone();')+ expect(client).toMatch(/postChatEvent\('assistant', finalText\);\s*syncCurrentChat\(\);\s*voiceAnswerDone\(\);/)+ })++ it('may play the voice of the computer (a blob: URL) under its CSP, and nothing from elsewhere', () => {+ expect(page).toMatch(/media-src 'self' blob:;/)+ expect(page).toMatch(/connect-src 'self';/)+ })++ it('says why the microphone does not open over the plain Wi-Fi address', () => {+ expect(client).toMatch(/window\.isSecureContext/)+ expect(client).toMatch(/insecure: '[^']*secure page[^']*LU app[^']*'/)+ })+})diff --git a/src/mobile/remote/remoteVoice.ts b/src/mobile/remote/remoteVoice.tsnew file mode 100644index 00000000..7450daba--- /dev/null+++ b/src/mobile/remote/remoteVoice.ts@@ -0,0 +1,310 @@+/**+ * Voice over remote (GitHub #212): talk to LU on the computer and hear the answer.+ *+ * The phone records one take at a time, the computer writes it down with its+ * own speech recognition (src-tauri/src/commands/remote_voice.rs), and the text+ * goes into the chat like a typed message. The answer is read with the voice+ * of this phone; a phone without one asks the computer to speak it.+ *+ * GET /remote-api/voice what the computer can do right now+ * POST /remote-api/voice/transcribe a WAV take, answers { text }+ * POST /remote-api/voice/speak { text }, answers a WAV+ *+ * Only inside the sealed channel, like Create and the shared chats. This file+ * holds the calls and the pure parts (when a sentence ended, what of an answer+ * is read aloud); screens/remote/parts/RemoteVoice.tsx drives them.+ */+import type { DesktopChannel } from './remoteClientStore'+import { RemoteError } from './remoteErrors'+import { sealedErrorPinned } from './sealedChannel'++export const FEATURE_VOICE = 'voice'++export const VOICE_PATHS = {+ status: '/remote-api/voice',+ transcribe: '/remote-api/voice/transcribe',+ speak: '/remote-api/voice/speak',+} as const++export const VOICE_TEXT = {+ unreachable: 'The computer did not answer.',+ protocol: 'The computer sent an answer this phone cannot read.',+ tooLong: 'That was too long. Keep a message under two minutes.',+ noListen: 'Speech recognition is not set up on the computer.',+ failed: 'The computer could not write down what you said.',+ tooOld: 'LU on the computer is too old for voice. Update it to 3.1.0 or newer.',+} as const++export interface ComputerVoice {+ /** The computer can write down a take. */+ listen: boolean+ /** The computer can read an answer aloud. */+ speak: boolean+ maxTakeBytes: number+ maxTakeMs: number+ maxSpeakChars: number+ /** The one thing to tell the user when `listen` is false, as the computer said it. */+ why: string | null+}++export type VoiceErrorCode = 'unreachable' | 'too-long' | 'no-listen' | 'no-speak' | 'failed' | 'too-old' | 'protocol' | 'aborted'++export class VoiceError extends Error {+ readonly code: VoiceErrorCode+ constructor(code: VoiceErrorCode, message: string) {+ super(message)+ this.name = 'VoiceError'+ this.code = code+ }+}++function rec(v: unknown): Record<string, unknown> | null {+ return v && typeof v === 'object' && !Array.isArray(v) ? (v as Record<string, unknown>) : null+}++function count(v: unknown, fallback: number): number {+ return typeof v === 'number' && Number.isFinite(v) && v > 0 ? Math.floor(v) : fallback+}++/** A sentence from the computer, kept short and plain. */+function sentence(v: unknown, max = 300): string {+ if (typeof v !== 'string') return ''+ const s = v.replace(/\s+/g, ' ').trim()+ return s.length > max ? `${s.slice(0, max - 1)}…` : s+}++/** Pure: the status answer of the computer. Anything missing counts as "cannot". */+export function readComputerVoice(raw: unknown): ComputerVoice {+ const o = rec(raw)+ return {+ listen: o?.listen === true,+ speak: o?.speak === true,+ maxTakeBytes: count(o?.max_take_bytes, 4 * 1024 * 1024),+ maxTakeMs: count(o?.max_take_ms, 120_000),+ maxSpeakChars: count(o?.max_speak_chars, 1500),+ why: sentence(o?.why) || null,+ }+}++/** Pure: an answer that is not 2xx, as what to tell the user. */+export function voiceErrorOf(status: number, body: unknown): VoiceError {+ const o = rec(body)+ const said = sentence(o?.message)+ if (status === 404 || status === 405) return new VoiceError('too-old', VOICE_TEXT.tooOld)+ if (status === 413) return new VoiceError('too-long', said || VOICE_TEXT.tooLong)+ if (status === 409 && o?.error === 'no_listen') return new VoiceError('no-listen', said || VOICE_TEXT.noListen)+ if (status === 409 && o?.error === 'no_speak') return new VoiceError('no-speak', said || VOICE_TEXT.failed)+ if (status === 502) return new VoiceError('failed', said || VOICE_TEXT.failed)+ if (status === 503) return new VoiceError('unreachable', said || VOICE_TEXT.unreachable)+ return new VoiceError('protocol', said || VOICE_TEXT.protocol)+}++function viaTunnel(ch: DesktopChannel): boolean {+ try {+ return new URL(ch.address).protocol === 'https:'+ } catch {+ return false+ }+}++function channelError(err: unknown, ch: DesktopChannel): VoiceError {+ if (err instanceof VoiceError) return err+ if (err instanceof Error && err.name === 'AbortError') return new VoiceError('aborted', 'Stopped.')+ const e = err instanceof RemoteError ? err : sealedErrorPinned(err, viaTunnel(ch))+ if (e.code === 'aborted') return new VoiceError('aborted', 'Stopped.')+ return new VoiceError('unreachable', e.userMessage || VOICE_TEXT.unreachable)+}++export function bytesToBase64(bytes: Uint8Array): string {+ let bin = ''+ const step = 0x8000+ for (let i = 0; i < bytes.length; i += step) bin += String.fromCharCode(...bytes.subarray(i, i + step))+ return btoa(bin)+}++export function base64ToBytes(text: string): Uint8Array {+ const bin = atob(text)+ const out = new Uint8Array(bin.length)+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i)+ return out+}++let callNumber = 0++/** One sealed request with a binary body or answer. */+async function sealedCall(+ ch: DesktopChannel,+ path: string,+ init: { method: 'GET' | 'POST'; contentType?: string; bytes?: Uint8Array; timeoutMs: number; signal?: AbortSignal },+): Promise<{ status: number; bytes: Uint8Array }> {+ callNumber += 1+ const callId = `voice-${Date.now().toString(36)}-${callNumber}`+ const onAbort = () => void ch.invoke('remote_sealed_cancel', { callId }).catch(() => {})+ init.signal?.addEventListener('abort', onAbort, { once: true })+ let answer: { status?: unknown; bodyBase64?: unknown }+ try {+ if (init.signal?.aborted) throw new VoiceError('aborted', 'Stopped.')+ answer = (await ch.invoke('remote_sealed_request', {+ baseUrl: ch.address,+ desktopId: ch.pin.desktopId,+ x25519: ch.pin.x25519,+ path,+ method: init.method,+ headers: { ...(init.contentType ? { 'content-type': init.contentType } : {}), accept: 'application/json, audio/wav' },+ body: null,+ bodyBase64: init.bytes ? bytesToBase64(init.bytes) : null,+ timeoutMs: init.timeoutMs,+ callId,+ deviceName: null,+ })) as { status?: unknown; bodyBase64?: unknown }+ } catch (err) {+ throw channelError(err, ch)+ } finally {+ init.signal?.removeEventListener('abort', onAbort)+ }+ const status = Number(answer?.status)+ let bytes: Uint8Array+ try {+ bytes = base64ToBytes(String(answer?.bodyBase64 ?? ''))+ } catch {+ bytes = new Uint8Array()+ }+ return { status: Number.isInteger(status) ? status : 0, bytes }+}++function jsonOf(bytes: Uint8Array): unknown {+ try {+ return JSON.parse(new TextDecoder().decode(bytes))+ } catch {+ return null+ }+}++/** What the computer can do right now. */+export async function getComputerVoice(ch: DesktopChannel, signal?: AbortSignal): Promise<ComputerVoice> {+ const { status, bytes } = await sealedCall(ch, VOICE_PATHS.status, { method: 'GET', timeoutMs: 15_000, signal })+ if (status < 200 || status >= 300) throw voiceErrorOf(status, jsonOf(bytes))+ return readComputerVoice(jsonOf(bytes))+}++/**+ * The text of a take. The first take after the computer started can wait for+ * its speech recognition to load, hence the long time.+ */+export async function transcribeOnComputer(ch: DesktopChannel, wav: Uint8Array, signal?: AbortSignal): Promise<string> {+ const { status, bytes } = await sealedCall(ch, VOICE_PATHS.transcribe, { method: 'POST', contentType: 'audio/wav', bytes: wav, timeoutMs: 180_000, signal })+ const data = jsonOf(bytes)+ if (status < 200 || status >= 300) throw voiceErrorOf(status, data)+ const text = rec(data)?.text+ if (typeof text !== 'string') throw new VoiceError('protocol', VOICE_TEXT.protocol)+ return text.trim()+}++/** A WAV of `text` in the voice of the computer. */+export async function speakOnComputer(ch: DesktopChannel, text: string, signal?: AbortSignal): Promise<Uint8Array> {+ const body = new TextEncoder().encode(JSON.stringify({ text }))+ const { status, bytes } = await sealedCall(ch, VOICE_PATHS.speak, { method: 'POST', contentType: 'application/json', bytes: body, timeoutMs: 60_000, signal })+ if (status < 200 || status >= 300) throw voiceErrorOf(status, jsonOf(bytes))+ return bytes+}++// ── pure: what of an answer is read aloud ───────────────────────++/**+ * Pure: the words of an answer, without what a voice should not read: code+ * blocks, the thought of a model, links written out, the marks of Markdown.+ */+export function speakableText(markdown: string): string {+ return markdown+ .replace(/<think>[\s\S]*?<\/think>/gi, ' ')+ .replace(/```[\s\S]*?(```|$)/g, ' ')+ .replace(/`([^`]+)`/g, '$1')+ .replace(/!\[[^\]]*\]\([^)]*\)/g, ' ')+ .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1')+ .replace(/https?:\/\/\S+/g, ' ')+ .replace(/^\s{0,3}#{1,6}\s+/gm, '')+ .replace(/^\s*[-*+]\s+/gm, '')+ .replace(/^\s*>\s?/gm, '')+ .replace(/(\*\*|__|\*|_|~~)(?=\S)([\s\S]*?\S)\1/g, '$2')+ .replace(/\|/g, ' ')+ .replace(/\s+/g, ' ')+ .trim()+}++/** Pure: the text in pieces of at most `max` characters, cut after a sentence where one ends in time. */+export function speechPieces(text: string, max: number): string[] {+ const out: string[] = []+ let rest = text.trim()+ while (rest.length > max) {+ const window = rest.slice(0, max)+ const end = Math.max(window.lastIndexOf('. '), window.lastIndexOf('! '), window.lastIndexOf('? '), window.lastIndexOf('\n'))+ const space = window.lastIndexOf(' ')+ const cut = end > max / 3 ? end + 1 : space > max / 3 ? space : max+ out.push(rest.slice(0, cut).trim())+ rest = rest.slice(cut).trim()+ }+ if (rest) out.push(rest)+ return out+}++// ── pure: when a sentence ended (hands free) ────────────────────++/** Above this level the phone hears speech. The meter's level is 0 to 1 (useVoice.ts, levelFromSamples). */+export const SPEECH_LEVEL = 0.1+/** Below this level it is quiet again. Lower than SPEECH_LEVEL, so a word that fades does not cut the take. */+export const QUIET_LEVEL = 0.05+/** Speech has to last this long to count; a cough or a click does not start a take. */+export const SPEECH_MIN_MS = 250+/** This much quiet after speech ends the sentence. */+export const END_QUIET_MS = 1100+/** Hands free stops listening after this long without anything said. */+export const GIVE_UP_MS = 30_000++export interface TurnState {+ /** When listening started. */+ since: number+ /** When the current run of loud readings started, or null. */+ loudSince: number | null+ /** Speech has been heard in this take. */+ heard: boolean+ /** When the current quiet started after speech, or null. */+ quietSince: number | null+}++export type TurnEvent = 'speech' | 'end' | 'give-up' | null++export function startTurn(now: number): TurnState {+ return { since: now, loudSince: null, heard: false, quietSince: null }+}++/**+ * Pure: one reading of the level. Hands free starts a take only after real+ * speech, ends it after a pause, and gives up after a long silence.+ */+export function nextTurn(state: TurnState, level: number, now: number): { state: TurnState; event: TurnEvent } {+ const l = Number.isFinite(level) ? level : 0+ if (!state.heard) {+ if (l >= SPEECH_LEVEL) {+ const loudSince = state.loudSince ?? now+ if (now - loudSince >= SPEECH_MIN_MS) return { state: { ...state, loudSince, heard: true, quietSince: null }, event: 'speech' }+ return { state: { ...state, loudSince }, event: null }+ }+ const next = { ...state, loudSince: l >= QUIET_LEVEL ? state.loudSince : null }+ if (now - state.since >= GIVE_UP_MS) return { state: next, event: 'give-up' }+ return { state: next, event: null }+ }+ if (l >= QUIET_LEVEL) return { state: { ...state, quietSince: null }, event: null }+ const quietSince = state.quietSince ?? now+ if (now - quietSince >= END_QUIET_MS) return { state: { ...state, quietSince }, event: 'end' }+ return { state: { ...state, quietSince }, event: null }+}++/** Pure: a press shorter than this on the microphone is a tap (hands free), a longer one is push to talk. */+export const HOLD_MS = 300++export function pressKind(downAt: number, upAt: number): 'tap' | 'hold' {+ return upAt - downAt >= HOLD_MS ? 'hold' : 'tap'+}++/** A take shorter than this holds no word and is not sent. */+export const MIN_TAKE_MS = 400diff --git a/src/mobile/screens/chat/parts/ComposerParts.tsx b/src/mobile/screens/chat/parts/ComposerParts.tsxindex 7f9fb343..145475de 100644--- a/src/mobile/screens/chat/parts/ComposerParts.tsx+++ b/src/mobile/screens/chat/parts/ComposerParts.tsx@@ -106,7 +106,7 @@ export function barHeights(level: number): number[] {* Their own component, so ten readings a second repaint five bars and* nothing else.*/-function LevelBars({ since }: { since: number }) {+export function LevelBars({ since }: { since: number }) {const level = useVoiceLevel()const [heard, setHeard] = useState(false)const [now, setNow] = useState(() => Date.now())diff --git a/src/mobile/screens/remote/RemoteChatPage.tsx b/src/mobile/screens/remote/RemoteChatPage.tsxindex cb4f4b5e..02996d0a 100644--- a/src/mobile/screens/remote/RemoteChatPage.tsx+++ b/src/mobile/screens/remote/RemoteChatPage.tsx@@ -39,6 +39,8 @@ import { openNewRemoteChat, sayOutcome } from './parts/actions'import { removePendingPhoto, restorePendingPhotos, takePendingPhotos, usePendingPhotos } from './parts/photos'import { remote, useKnownDesktops, useRemote } from './parts/session'import { Steps } from './parts/Steps'+import { RemoteVoiceLine, useRemoteVoice } from './parts/RemoteVoice'+import { FEATURE_VOICE } from '../../remote/remoteVoice'import { actionLabel, chatDesktopName, remoteModelLabel, desktopName, isForeignChat, messageFooter, sendBlocked, unansweredAction, type MessageAction } from './parts/view'import './parts/remote.css'@@ -226,6 +228,24 @@ export default function RemoteChatPage() {const draft = useRemote((s) => s.drafts[id] ?? '')const known = useKnownDesktops()const photos = usePendingPhotos(id)+ const features = useRemote((s) => s.features)+ const lastAnswer = chat ? [...chat.messages].reverse().find((m) => m.role === 'assistant') : undefined+ const voiceForeign = chat ? isForeignChat(chat, connection) : true+ // Voice over remote (#212): hold the microphone to talk, tap it for hands free.+ const voice = useRemoteVoice({+ channel: () => remote().desktopChannel(),+ ready: !!chat && status === 'connected' && !voiceForeign && features.includes(FEATURE_VOICE) && remote().desktopChannel() !== null,+ send: async (text) => {+ if (!chat) return false+ const state = remote()+ state.selectChat(chat.id)+ const outcome = await state.sendMessage(text)+ if (outcome !== 'sent') sayOutcome(outcome, chat.id)+ return outcome === 'sent'+ },+ busy: !!chat && streamingChatId === chat.id,+ lastAnswer: lastAnswer ? { id: lastAnswer.id, text: lastAnswer.state === 'failed' ? '' : lastAnswer.content } : null,+ })useEffect(() => {// The store sends into its active chat; this page is that chat while it is open.@@ -332,6 +352,9 @@ export default function RemoteChatPage() {el: 'R4.5',}}attach={{ label: S.chat.attach, onPress: () => nav.openSheet('remote-attach', { chatId: chat.id }), testid: 'm-remote-chat-attach', el: 'R4.9' }}+ micHold={voice.micHold}+ dictation={voice.dictation}+ replaceField={voice.phase !== 'off' ? <RemoteVoiceLine voice={voice} /> : undefined}/>}>diff --git a/src/mobile/screens/remote/SharedChatPage.tsx b/src/mobile/screens/remote/SharedChatPage.tsxindex f59100e4..df022424 100644--- a/src/mobile/screens/remote/SharedChatPage.tsx+++ b/src/mobile/screens/remote/SharedChatPage.tsx@@ -37,7 +37,9 @@ import { Button, Composer, EmptyState, Icon, IconButton, Notice, Page, SkeletonRimport { Markdown } from '../../ui/Markdown'import { ConnectionLine } from './parts/ConnectionLine'import { offerRemoteNotices } from './parts/notices'-import { useRemote } from './parts/session'+import { remote, useRemote } from './parts/session'+import { RemoteVoiceLine, useRemoteVoice } from './parts/RemoteVoice'+import { FEATURE_VOICE } from '../../remote/remoteVoice'import { remoteModelLabel, stepTitle } from './parts/view'import './parts/remote.css'@@ -326,6 +328,16 @@ export default function SharedChatPage() {const hydrated = useRemote((s) => s.hydrated)const [draft, setDraft] = useState('')const [files, setFiles] = useState<PickedAttachment[]>([])+ const status = useRemote((s) => s.status)+ const lastAnswer = view ? [...view.messages].reverse().find((m) => m.role === 'assistant') : undefined+ // Voice over remote (#212): hold the microphone to talk, tap it for hands free.+ const voice = useRemoteVoice({+ channel: () => remote().desktopChannel(),+ ready: status === 'connected' && sharesChats(features) && features.includes(FEATURE_VOICE) && remote().desktopChannel() !== null,+ send: (text) => sendShared(id, text, []) !== null,+ busy: !!view?.busy,+ lastAnswer: lastAnswer ? { id: lastAnswer.id, text: lastAnswer.content } : null,+ })useEffect(() => {if (!hydrated) return@@ -409,6 +421,9 @@ export default function SharedChatPage() {testid: 'm-remote-shared-model',}}attach={<IconButton icon={Paperclip} label={S.shared.attach} onPress={() => void attach()} risk="sensor" testid="m-remote-shared-attach" />}+ micHold={voice.micHold}+ dictation={voice.dictation}+ replaceField={voice.phase !== 'off' ? <RemoteVoiceLine voice={voice} /> : undefined}/>}>diff --git a/src/mobile/screens/remote/__tests__/remote-voice-flow.dom.test.tsx b/src/mobile/screens/remote/__tests__/remote-voice-flow.dom.test.tsxnew file mode 100644index 00000000..7a6b0dac--- /dev/null+++ b/src/mobile/screens/remote/__tests__/remote-voice-flow.dom.test.tsx@@ -0,0 +1,250 @@+// @vitest-environment jsdom+/**+ * Voice over remote (GitHub #212), the whole turn in a chat with the computer:+ * hold to talk sends one message and reads the answer; a tap is hands free,+ * which hears the end of a sentence, reads the answer and listens again until+ * End. The microphone, the voice of the phone and the computer are fakes; the+ * hook, the composer and the line in place of the field are the real ones.+ *+ * Run: npx vitest run src/mobile/screens/remote/__tests__/remote-voice-flow.dom.test.tsx+ */+import { useState } from 'react'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'++const fake = vi.hoisted(() => ({+ level: 0,+ takes: 0,+ stops: 0,+ sentTakes: [] as number[],+ spoken: [] as string[],+ computer: { listen: true, speak: false, why: null as string | null },+ transcript: 'what time is it',+}))++vi.mock('../../../../api/voice', () => ({+ createAudioRecorder: () => ({+ start: async () => {},+ stop: async () => {+ fake.stops += 1+ return new Blob([new Uint8Array(2000)], { type: 'audio/wav' })+ },+ }),+ playNeuralAudio: async () => {},+ stopNeuralAudio: () => {},+}))+vi.mock('../../../../hooks/useVoice', () => ({+ startRecorderWithStream: async () => {+ fake.takes += 1+ return {} as MediaStream+ },+ startLevelMeter: () => ({ stop: () => {} }),+ voiceLevel: () => fake.level,+ useVoiceLevel: () => fake.level,+}))+vi.mock('../../../lib/speech', () => ({+ listPhoneVoices: async () => ({ source: 'web', voices: [] }),+ speakOnDevice: async (words: string) => {+ fake.spoken.push(words)+ return { source: 'web', spoken: true }+ },+ stopDeviceSpeech: async () => {},+}))+vi.mock('../../../remote/remoteVoice', async (orig) => {+ const real = await orig<typeof import('../../../remote/remoteVoice')>()+ return {+ ...real,+ getComputerVoice: async () => ({ ...fake.computer, maxTakeBytes: 4e6, maxTakeMs: 120000, maxSpeakChars: 1500 }),+ transcribeOnComputer: async (_ch: unknown, wav: Uint8Array) => {+ fake.sentTakes.push(wav.length)+ return fake.transcript+ },+ }+})++import { Composer } from '../../../ui'+import { RemoteVoiceLine, useRemoteVoice } from '../parts/RemoteVoice'+import { useMobilePrefs } from '../../settings/parts/prefs'++const channel = { address: 'http://lan', pin: { desktopId: 'd', x25519: 'k' }, invoke: async () => ({}), fetch: async () => new Response(), features: ['voice'] }++/** A chat that answers each message after `answerMs`. */+function Chat({ answerMs = 500 }: { answerMs?: number }) {+ const [messages, setMessages] = useState<Array<{ id: string; role: string; text: string }>>([])+ const [busy, setBusy] = useState(false)+ const last = [...messages].reverse().find((m) => m.role === 'assistant')+ const voice = useRemoteVoice({+ channel: () => channel as never,+ ready: true,+ send: (text) => {+ setMessages((m) => [...m, { id: `u${m.length}`, role: 'user', text }])+ setBusy(true)+ setTimeout(() => {+ setMessages((m) => [...m, { id: `a${m.length}`, role: 'assistant', text: `**It is** noon. (${text})` }])+ setBusy(false)+ }, answerMs)+ return true+ },+ busy,+ lastAnswer: last ? { id: last.id, text: last.text } : null,+ })+ return (+ <>+ <ol data-testid="msgs">{messages.map((m) => <li key={m.id}>{m.role}: {m.text}</li>)}</ol>+ <Composer value="" onChange={() => {}} onSend={() => {}} running={busy} onStop={() => {}} idPrefix="m-remote-chat" micHold={voice.micHold} dictation={voice.dictation} replaceField={voice.phase !== 'off' ? <RemoteVoiceLine voice={voice} /> : undefined} />+ </>+ )+}++const flush = async (ms = 0) => {+ await act(async () => {+ await vi.advanceTimersByTimeAsync(ms)+ })+}++beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: false })+ Object.assign(fake, { level: 0, takes: 0, stops: 0, sentTakes: [], spoken: [], computer: { listen: true, speak: false, why: null }, transcript: 'what time is it' })+ useMobilePrefs.setState({ remoteVoiceReadAloud: true })+})+afterEach(() => {+ cleanup()+ vi.useRealTimers()+})++describe('push to talk', () => {+ it('hold, talk, let go: one message, the answer is read, then the field is back', async () => {+ render(<Chat />)+ const mic = screen.getByTestId('m-remote-chat-mic')+ await act(async () => {+ fireEvent.pointerDown(mic, { button: 0, pointerId: 1 })+ })+ await flush(10)+ expect(screen.getByTestId('m-remote-voice').getAttribute('data-state')).toBe('recording')+ fake.level = 0.4+ await flush(1200)+ await act(async () => {+ fireEvent.pointerUp(screen.getByTestId('m-remote-chat-mic'), { pointerId: 1 })+ })+ await flush(10)+ expect(fake.sentTakes).toHaveLength(1)+ expect(screen.getByTestId('msgs').textContent).toContain('user: what time is it')+ expect(screen.getByTestId('m-remote-voice').getAttribute('data-state')).toBe('waiting')+ await flush(600)+ expect(fake.spoken).toEqual(['It is noon. (what time is it)'])+ await flush(10)+ expect(screen.queryByTestId('m-remote-voice')).toBeNull()+ expect(screen.getByTestId('m-remote-chat-input')).toBeTruthy()+ expect(fake.takes).toBe(1)+ })++ it('a press too short to hold a word sends nothing', async () => {+ render(<Chat />)+ const mic = screen.getByTestId('m-remote-chat-mic')+ await act(async () => {+ fireEvent.pointerDown(mic, { button: 0, pointerId: 1 })+ })+ await flush(350)+ await act(async () => {+ fireEvent.pointerUp(screen.getByTestId('m-remote-chat-mic'), { pointerId: 1 })+ })+ await flush(10)+ expect(fake.sentTakes).toHaveLength(0)+ expect(screen.queryByTestId('m-remote-voice')).toBeNull()+ })++ it('with Read the answer aloud off, nothing is read', async () => {+ useMobilePrefs.setState({ remoteVoiceReadAloud: false })+ render(<Chat />)+ const mic = screen.getByTestId('m-remote-chat-mic')+ await act(async () => {+ fireEvent.pointerDown(mic, { button: 0, pointerId: 1 })+ })+ await flush(1000)+ await act(async () => {+ fireEvent.pointerUp(screen.getByTestId('m-remote-chat-mic'), { pointerId: 1 })+ })+ await flush(700)+ expect(fake.sentTakes).toHaveLength(1)+ expect(fake.spoken).toEqual([])+ expect(screen.queryByTestId('m-remote-voice')).toBeNull()+ })++ it('without speech recognition on the computer, the reason and no recording', async () => {+ fake.computer = { listen: false, speak: false, why: 'Install speech to text on the computer.' }+ render(<Chat />)+ await act(async () => {+ fireEvent.pointerDown(screen.getByTestId('m-remote-chat-mic'), { button: 0, pointerId: 1 })+ })+ await flush(10)+ expect(fake.takes).toBe(0)+ expect(screen.queryByTestId('m-remote-voice')).toBeNull()+ })+})++describe('hands free', () => {+ it('a tap listens; a sentence and a pause send it, the answer is read, it listens again until End', async () => {+ render(<Chat />)+ const mic = screen.getByTestId('m-remote-chat-mic')+ await act(async () => {+ fireEvent.pointerDown(mic, { button: 0, pointerId: 1 })+ fireEvent.pointerUp(mic, { pointerId: 1 })+ })+ await flush(10)+ const line = screen.getByTestId('m-remote-voice')+ expect(line.getAttribute('data-m-mode')).toBe('free')+ // Quiet before speaking: nothing is sent.+ await flush(2000)+ expect(fake.sentTakes).toHaveLength(0)+ fake.level = 0.4+ await flush(1500)+ fake.level = 0.01+ await flush(1400)+ expect(fake.sentTakes).toHaveLength(1)+ await flush(600)+ expect(fake.spoken).toHaveLength(1)+ await flush(20)+ // Listening again.+ expect(fake.takes).toBe(2)+ expect(screen.getByTestId('m-remote-voice').getAttribute('data-state')).toBe('recording')+ await act(async () => {+ fireEvent.click(screen.getByTestId('m-remote-voice-end'))+ })+ await flush(10)+ expect(screen.queryByTestId('m-remote-voice')).toBeNull()+ expect(fake.sentTakes).toHaveLength(1)+ })++ it('a long silence ends hands free', async () => {+ render(<Chat />)+ const mic = screen.getByTestId('m-remote-chat-mic')+ await act(async () => {+ fireEvent.pointerDown(mic, { button: 0, pointerId: 1 })+ fireEvent.pointerUp(mic, { pointerId: 1 })+ })+ await flush(31_000)+ expect(screen.queryByTestId('m-remote-voice')).toBeNull()+ expect(fake.sentTakes).toHaveLength(0)+ })++ it('a press while the answer is read stops the reading and starts a new take', async () => {+ render(<Chat answerMs={100} />)+ let mic = screen.getByTestId('m-remote-chat-mic')+ await act(async () => {+ fireEvent.pointerDown(mic, { button: 0, pointerId: 1 })+ })+ await flush(900)+ await act(async () => {+ fireEvent.pointerUp(screen.getByTestId('m-remote-chat-mic'), { pointerId: 1 })+ })+ // The fake voice resolves at once; stop it in the speaking phase by holding it there.+ await flush(150)+ mic = screen.getByTestId('m-remote-chat-mic')+ await act(async () => {+ fireEvent.pointerDown(mic, { button: 0, pointerId: 2 })+ })+ await flush(10)+ expect(screen.getByTestId('m-remote-voice').getAttribute('data-state')).toBe('recording')+ expect(fake.takes).toBe(2)+ })+})diff --git a/src/mobile/screens/remote/parts/RemoteVoice.tsx b/src/mobile/screens/remote/parts/RemoteVoice.tsxnew file mode 100644index 00000000..eb7be032--- /dev/null+++ b/src/mobile/screens/remote/parts/RemoteVoice.tsx@@ -0,0 +1,442 @@+/**+ * Voice over remote in a chat with the computer (GitHub #212).+ *+ * The microphone in the composer knows two ways:+ *+ * hold push to talk. The take runs while the finger is on the microphone+ * and is sent when it lifts.+ * tap hands free. LU listens, hears the end of a sentence by itself+ * (remote/remoteVoice.ts, nextTurn), sends it, reads the answer aloud+ * and listens again, until End or a long silence.+ *+ * The computer writes the take down (remote_voice.rs), the text goes into the+ * chat like a typed message. The answer is read with the voice of this phone+ * and the voice the user picked in Settings, Voice; a phone without a voice+ * asks the computer to speak it. Whether the answer is read at all is the one+ * switch in Settings, Voice ("Voice with your computer").+ *+ * While a turn runs, the text field gives its place to one line: the level of+ * the microphone, what happens, and End. Nothing else is added to the page.+ */+import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'+import { Volume2 } from 'lucide-react'+import { createAudioRecorder, playNeuralAudio, stopNeuralAudio, type AudioRecorder } from '../../../../api/voice'+import { startLevelMeter, startRecorderWithStream, voiceLevel, type LevelMeter } from '../../../../hooks/useVoice'+import { systemVoiceFallbackAllowed } from '../../../../lib/mobile-prefs'+import { useVoiceStore } from '../../../../stores/voiceStore'+import { listPhoneVoices, speakOnDevice, stopDeviceSpeech } from '../../../lib/speech'+import {+ getComputerVoice,+ MIN_TAKE_MS,+ nextTurn,+ pressKind,+ speakableText,+ speakOnComputer,+ speechPieces,+ startTurn,+ transcribeOnComputer,+ VoiceError,+ type ComputerVoice,+ type TurnState,+} from '../../../remote/remoteVoice'+import type { DesktopChannel } from '../../../remote/remoteClientStore'+import { REMOTE_STRINGS } from '../../../strings/remote'+import { Icon, Spinner, toast, type ComposerMicHold } from '../../../ui'+import { LevelBars, useClock } from '../../chat/parts/ComposerParts'+import { readingLanguage } from '../../chat/parts/voice-pref'+import { useMobilePrefs } from '../../settings/parts/prefs'++const S = REMOTE_STRINGS.voice++export type VoicePhase = 'off' | 'recording' | 'sending' | 'waiting' | 'speaking'+export type VoiceMode = 'hold' | 'free'++export interface RemoteVoiceOptions {+ /** The sealed channel to the computer, or null: then there is no microphone. */+ channel: () => DesktopChannel | null+ /** The computer offers voice (feature `voice`) and the chat can be written to. */+ ready: boolean+ /** Put the text into the chat as a message. False when it could not be sent; the page says why. */+ send: (text: string) => boolean | Promise<boolean>+ /** An answer is being written. */+ busy: boolean+ /** The last answer of the chat, to read the new one aloud. */+ lastAnswer: { id: string; text: string } | null+}++export interface RemoteVoice {+ phase: VoicePhase+ mode: VoiceMode | null+ since: number | null+ /** For the composer: undefined while the computer offers no voice. */+ micHold: ComposerMicHold | undefined+ /** For the composer's microphone slot. */+ dictation: 'recording' | 'transcribing' | undefined+ end: () => void+ /** Stop reading and listen (hands free) or stop (push to talk). */+ interrupt: () => void+}++/** How often hands free reads the level. The meter itself measures every 90 ms (useVoice.ts). */+const TURN_EVERY_MS = 90+/** The status of the computer is asked again after this long. */+const VOICE_STATUS_MS = 30_000++interface Run {+ token: number+ recorder: AudioRecorder | null+ meter: LevelMeter | null+ starting: Promise<boolean> | null+ downAt: number+ startAt: number+ /** The finger lifted before the recorder was ready: what it decided. */+ pendingUp: 'tap' | 'hold' | null+ turn: TurnState | null+ timer: number | null+ abort: AbortController | null+ answerBefore: string | null+ computer: { at: number; voice: ComputerVoice } | null+}++function microphoneMessage(err: unknown): string {+ const name = err instanceof Error ? err.name : ''+ if (name === 'NotAllowedError' || name === 'SecurityError') return S.micDenied+ return S.noMic+}++export function useRemoteVoice(options: RemoteVoiceOptions): RemoteVoice {+ const [phase, setPhase] = useState<VoicePhase>('off')+ const [mode, setMode] = useState<VoiceMode | null>(null)+ const [since, setSince] = useState<number | null>(null)+ const live = useRef(options)+ live.current = options+ const modeRef = useRef<VoiceMode | null>(null)+ const run = useRef<Run>({ token: 0, recorder: null, meter: null, starting: null, downAt: 0, startAt: 0, pendingUp: null, turn: null, timer: null, abort: null, answerBefore: null, computer: null })++ const setModeBoth = (next: VoiceMode | null) => {+ modeRef.current = next+ setMode(next)+ }++ const stopListening = () => {+ const r = run.current+ if (r.timer !== null) window.clearInterval(r.timer)+ r.timer = null+ r.turn = null+ try {+ r.meter?.stop()+ } catch {+ /* the meter goes anyway */+ }+ r.meter = null+ }++ const end = useCallback(() => {+ const r = run.current+ r.token += 1+ stopListening()+ r.abort?.abort()+ r.abort = null+ const recorder = r.recorder+ r.recorder = null+ r.starting = null+ r.pendingUp = null+ if (recorder) void recorder.stop().catch(() => {})+ void stopDeviceSpeech()+ stopNeuralAudio()+ setPhase('off')+ setModeBoth(null)+ setSince(null)+ }, [])++ useEffect(() => end, [end])++ /** What the computer can do, asked at most every 30 s. */+ const computer = async (ch: DesktopChannel): Promise<ComputerVoice> => {+ const r = run.current+ if (r.computer && Date.now() - r.computer.at < VOICE_STATUS_MS) return r.computer.voice+ const voice = await getComputerVoice(ch)+ r.computer = { at: Date.now(), voice }+ return voice+ }++ // Ask early, so the first press does not wait for it.+ useEffect(() => {+ if (!options.ready) return+ const ch = options.channel()+ if (ch) void computer(ch).catch(() => {})+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [options.ready])++ const fail = (message: string) => {+ end()+ toast(message, { tone: 'error', testid: 'm-remote-voice-failed' })+ }++ /** Start a take. Hands free also starts listening for the end of a sentence. */+ const startTake = (token: number): Promise<boolean> => {+ const r = run.current+ const recorder = createAudioRecorder()+ const starting = (async () => {+ let stream: MediaStream | null+ try {+ stream = await startRecorderWithStream(recorder)+ } catch (err) {+ if (token === r.token) fail(microphoneMessage(err))+ return false+ }+ if (token !== r.token) {+ void recorder.stop().catch(() => {})+ return false+ }+ r.recorder = recorder+ r.meter = stream ? startLevelMeter(stream) : null+ r.startAt = Date.now()+ setSince(r.startAt)+ setPhase('recording')+ return true+ })()+ r.starting = starting+ return starting+ }++ const listenFree = (token: number) => {+ const r = run.current+ r.turn = startTurn(Date.now())+ if (r.timer !== null) window.clearInterval(r.timer)+ r.timer = window.setInterval(() => {+ if (token !== r.token || !r.turn) return+ const { state, event } = nextTurn(r.turn, voiceLevel(), Date.now())+ r.turn = state+ if (event === 'end') void finishTake(token)+ else if (event === 'give-up') {+ end()+ toast(S.gaveUp, { testid: 'm-remote-voice-gave-up' })+ }+ }, TURN_EVERY_MS)+ }++ /** Hands free: listen for the next sentence. */+ const listenAgain = async (token: number) => {+ if (token !== run.current.token) return+ if (await startTake(token)) listenFree(token)+ }++ const finishTake = async (token: number) => {+ const r = run.current+ if (token !== r.token) return+ const recorder = r.recorder+ r.recorder = null+ stopListening()+ if (!recorder) return+ const free = modeRef.current === 'free'+ const heard = free ? true : Date.now() - r.startAt >= MIN_TAKE_MS+ const blob = await recorder.stop().catch(() => null)+ if (token !== r.token) return+ if (!heard || !blob || blob.size <= 44) {+ if (free) return void listenAgain(token)+ end()+ toast(S.nothingHeard, { testid: 'm-remote-voice-nothing' })+ return+ }+ setPhase('sending')+ const ch = live.current.channel()+ if (!ch) return fail(S.notConnected)+ const abort = new AbortController()+ r.abort = abort+ let text: string+ try {+ text = await transcribeOnComputer(ch, new Uint8Array(await blob.arrayBuffer()), abort.signal)+ } catch (err) {+ if (token !== r.token || (err instanceof VoiceError && err.code === 'aborted')) return+ // The computer may have changed: ask it again next time.+ r.computer = null+ return fail(err instanceof Error ? err.message : String(err))+ } finally {+ if (r.abort === abort) r.abort = null+ }+ if (token !== r.token) return+ if (!text) {+ if (free) return void listenAgain(token)+ end()+ toast(S.nothingHeard, { testid: 'm-remote-voice-nothing' })+ return+ }+ r.answerBefore = live.current.lastAnswer?.id ?? null+ if (!(await live.current.send(text))) {+ end()+ return+ }+ if (token !== r.token) return+ setPhase('waiting')+ }++ const afterAnswer = (token: number) => {+ if (token !== run.current.token) return+ if (modeRef.current === 'free') void listenAgain(token)+ else end()+ }++ const speakAnswer = async (token: number, answer: string) => {+ const words = speakableText(answer)+ if (!useMobilePrefs.getState().remoteVoiceReadAloud || !words) return afterAnswer(token)+ setPhase('speaking')+ try {+ const phone = await listPhoneVoices()+ if (token !== run.current.token) return+ if (phone.source !== 'none' && systemVoiceFallbackAllowed()) {+ const v = useVoiceStore.getState()+ await speakOnDevice(words, { voiceId: v.ttsVoice || undefined, rate: v.ttsRate, pitch: v.ttsPitch, lang: readingLanguage(words, navigator.language) })+ } else {+ const ch = live.current.channel()+ if (!ch) return fail(S.notConnected)+ const can = await computer(ch)+ if (!can.speak) return afterAnswer(token)+ const pieces = speechPieces(words, can.maxSpeakChars)+ // The next piece is fetched while this one plays.+ let next: Promise<Uint8Array> | null = pieces.length ? speakOnComputer(ch, pieces[0]) : null+ for (let i = 0; i < pieces.length && next; i++) {+ const wav = await next+ if (token !== run.current.token) return+ next = i + 1 < pieces.length ? speakOnComputer(ch, pieces[i + 1]) : null+ await playNeuralAudio(URL.createObjectURL(new Blob([wav as BlobPart], { type: 'audio/wav' })))+ if (token !== run.current.token) return+ }+ }+ } catch {+ if (token !== run.current.token) return+ toast(S.speakFailed, { testid: 'm-remote-voice-speak-failed' })+ }+ afterAnswer(token)+ }++ // The answer is there when the chat is no longer busy and its last answer is a new one.+ const answerId = options.lastAnswer?.id ?? null+ const answerText = options.lastAnswer?.text ?? ''+ useEffect(() => {+ if (phase !== 'waiting' || options.busy) return+ if (!answerId || answerId === run.current.answerBefore) return+ void speakAnswer(run.current.token, answerText)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [phase, options.busy, answerId, answerText])++ const onDown = async () => {+ const r = run.current+ // A press while the answer is read: the reading stops and a new take starts (barge in).+ if (phase === 'speaking' || phase === 'waiting') {+ r.token += 1+ r.abort?.abort()+ void stopDeviceSpeech()+ stopNeuralAudio()+ } else if (phase === 'recording' && modeRef.current === 'free') {+ // Hands free, a tap while it listens: the sentence is done, send it now.+ return void finishTake(r.token)+ } else if (phase !== 'off') {+ return+ }+ const ch = live.current.channel()+ if (!ch) return fail(S.notConnected)+ const token = r.token+ r.downAt = Date.now()+ r.pendingUp = null+ setModeBoth(null)+ try {+ const can = await computer(ch)+ if (token !== r.token) return+ if (!can.listen) return fail(can.why || S.notConnected)+ } catch (err) {+ return fail(err instanceof Error ? err.message : String(err))+ }+ const started = await startTake(token)+ if (!started || token !== r.token) return+ // The finger may have lifted while the recorder started.+ if (r.pendingUp) decide(token, r.pendingUp)+ }++ const decide = (token: number, kind: 'tap' | 'hold') => {+ const r = run.current+ r.pendingUp = null+ if (kind === 'hold') {+ setModeBoth('hold')+ void finishTake(token)+ } else {+ setModeBoth('free')+ listenFree(token)+ }+ }++ const onUp = () => {+ const r = run.current+ const kind = pressKind(r.downAt, Date.now())+ if (modeRef.current === 'free') return+ if (!r.recorder) {+ r.pendingUp = kind+ return+ }+ decide(r.token, kind)+ }++ const interrupt = () => {+ const r = run.current+ r.token += 1+ void stopDeviceSpeech()+ stopNeuralAudio()+ if (modeRef.current === 'free') void listenAgain(r.token)+ else end()+ }++ return {+ phase,+ mode,+ since,+ micHold: options.ready ? { onDown: () => void onDown(), onUp, label: S.mic } : undefined,+ dictation: phase === 'recording' ? 'recording' : phase === 'sending' ? 'transcribing' : undefined,+ end,+ interrupt,+ }+}++function Clock({ since }: { since: number }) {+ return <span className="m-rvoice-clock">{useClock(since)}</span>+}++/** The line in place of the text field while a voice turn runs. Null when nothing runs. */+export function RemoteVoiceLine({ voice }: { voice: RemoteVoice }): ReactNode {+ const { phase, mode, since } = voice+ if (phase === 'off') return null+ const endButton = mode === 'hold' && phase === 'recording' ? null : (+ <button type="button" className="m-rvoice-end" aria-label={S.endName} data-testid="m-remote-voice-end" onClick={voice.end}>+ {S.end}+ </button>+ )+ if (phase === 'recording' && since !== null) {+ return (+ <div className="m-rvoice" role="status" data-testid="m-remote-voice" data-state="recording" data-m-mode={mode ?? 'pending'}>+ <LevelBars since={since} />+ <Clock since={since} />+ <span className="m-rvoice-hint">{mode === 'free' ? S.listening : S.talk}</span>+ {endButton}+ </div>+ )+ }+ if (phase === 'speaking') {+ return (+ <div className="m-rvoice" data-testid="m-remote-voice" data-state="speaking" data-m-mode={mode ?? undefined}>+ <button type="button" className="m-rvoice-tap" onClick={voice.interrupt} data-testid="m-remote-voice-interrupt">+ <Icon icon={Volume2} small />+ <span className="m-rvoice-hint">{S.speaking}</span>+ <span className="m-rvoice-sub">{S.interrupt}</span>+ </button>+ {endButton}+ </div>+ )+ }+ const label = phase === 'sending' ? S.sending : S.waiting+ return (+ <div className="m-rvoice" role="status" data-testid="m-remote-voice" data-state={phase} data-m-mode={mode ?? undefined}>+ <Spinner label={label} />+ <span className="m-rvoice-hint">{label}</span>+ {endButton}+ </div>+ )+}diff --git a/src/mobile/screens/remote/parts/remote.css b/src/mobile/screens/remote/parts/remote.cssindex 71ef0cda..13258c3b 100644--- a/src/mobile/screens/remote/parts/remote.css+++ b/src/mobile/screens/remote/parts/remote.css@@ -575,3 +575,82 @@display: block;color: var(--m-t3);}++/* ---------- Voice over remote (GitHub #212): the line in place of the text field ---------- */+.m-app .m-rvoice {+ width: 100%;+ min-height: 2.75rem;+ display: flex;+ align-items: center;+ gap: var(--m-s3);+ padding: 12px 14px 4px;+ color: var(--m-t1);+ font-size: var(--m-text-control);+}+.m-app .m-rvoice .m-chat-meter-bars {+ flex: none;+ display: inline-flex;+ align-items: center;+ gap: 3px;+ height: 20px;+}+.m-app .m-rvoice .m-chat-meter-bars i {+ width: 3px;+ height: 100%;+ border-radius: 2px;+ background: var(--m-err);+ transform-origin: center;+ transition: transform 90ms linear;+}+@media (prefers-reduced-motion: reduce) {+ .m-app .m-rvoice .m-chat-meter-bars i {+ transition: none;+ }+}+.m-app .m-rvoice .m-chat-meter-quiet {+ color: var(--m-t3);+ font-size: var(--m-text-caption);+}+.m-app .m-rvoice-clock {+ font-family: var(--m-font-mono);+ font-size: var(--m-text-mono);+ color: var(--m-t2);+}+.m-app .m-rvoice-hint {+ flex: 1 1 auto;+ min-width: 0;+ color: var(--m-t2);+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.m-app .m-rvoice-tap {+ flex: 1 1 auto;+ min-width: 0;+ min-height: 44px;+ display: flex;+ align-items: center;+ gap: var(--m-s2);+ padding: 0;+ border: 0;+ background: none;+ color: inherit;+ font: inherit;+ text-align: left;+}+.m-app .m-rvoice-sub {+ color: var(--m-t3);+ font-size: var(--m-text-caption);+ white-space: nowrap;+}+.m-app .m-rvoice-end {+ flex: none;+ min-height: 44px;+ min-width: 44px;+ padding: 0 var(--m-s2);+ border: 0;+ background: none;+ color: var(--m-t1);+ font: inherit;+ font-weight: 600;+}diff --git a/src/mobile/screens/settings/VoicePage.tsx b/src/mobile/screens/settings/VoicePage.tsxindex 283709e1..fc3f4839 100644--- a/src/mobile/screens/settings/VoicePage.tsx+++ b/src/mobile/screens/settings/VoicePage.tsx@@ -121,6 +121,7 @@ export default function VoicePage() {const pitch = useVoiceStore((s) => s.ttsPitch)const update = useVoiceStore((s) => s.updateVoiceSettings)const systemFallback = useMobilePrefs((s) => s.systemVoiceFallback)+ const remoteReadAloud = useMobilePrefs((s) => s.remoteVoiceReadAloud)const setPref = useMobilePrefs((s) => s.setPref)const micDenied = useMicDenied()const online = useCloudOnline()@@ -441,6 +442,17 @@ export default function VoicePage() {</Button></Block>+ <ListGroup title={T.remoteGroup} testid="m-settings-voice-remote">+ <Row+ title={T.remoteReadAloud}+ subtitle={T.remoteReadAloudSub}+ switch={{ checked: remoteReadAloud, onChange: (next) => setPref('remoteVoiceReadAloud', next) }}+ testid="m-settings-voice-remote-read"+ />+ </ListGroup>+ <Block>+ <Hint testid="m-settings-voice-remote-how">{T.remoteHow}</Hint>+ </Block></div></Page>)diff --git a/src/mobile/screens/settings/parts/prefs.ts b/src/mobile/screens/settings/parts/prefs.tsindex af434b0b..6829d5df 100644--- a/src/mobile/screens/settings/parts/prefs.ts+++ b/src/mobile/screens/settings/parts/prefs.ts@@ -28,10 +28,12 @@ export interface MobilePrefs {teaserHintShown: boolean/** E19: the last engine self test that passed, for the row "Last speed". null: never. */lastSelfTest: SelfTestRecord | null+ /** GitHub #212: after a voice message to the computer the answer is read aloud. Default on. */+ remoteVoiceReadAloud: booleansetPref: <K extends keyof MobilePrefValues>(key: K, value: MobilePrefValues[K]) => void}-export type MobilePrefValues = Pick<MobilePrefs, 'switchCounter' | 'systemVoiceFallback' | 'lastBackupAt' | 'teaserHintShown' | 'lastSelfTest'>+export type MobilePrefValues = Pick<MobilePrefs, 'switchCounter' | 'systemVoiceFallback' | 'lastBackupAt' | 'teaserHintShown' | 'lastSelfTest' | 'remoteVoiceReadAloud'>export const MOBILE_PREF_DEFAULTS: MobilePrefValues = {switchCounter: true,@@ -39,6 +41,7 @@ export const MOBILE_PREF_DEFAULTS: MobilePrefValues = {lastBackupAt: 0,teaserHintShown: false,lastSelfTest: null,+ remoteVoiceReadAloud: true,}export const useMobilePrefs = create<MobilePrefs>()(@@ -56,6 +59,7 @@ export const useMobilePrefs = create<MobilePrefs>()(lastBackupAt: s.lastBackupAt,teaserHintShown: s.teaserHintShown,lastSelfTest: s.lastSelfTest,+ remoteVoiceReadAloud: s.remoteVoiceReadAloud,}),},),diff --git a/src/mobile/strings/remote.ts b/src/mobile/strings/remote.tsindex 303b5bb4..2fb8a150 100644--- a/src/mobile/strings/remote.ts+++ b/src/mobile/strings/remote.ts@@ -547,6 +547,24 @@ export const REMOTE_STRINGS = {openSettings: 'Open settings',settingsFailed: 'The settings of your phone could not be opened.',},+ // ---- Voice over remote (GitHub #212) ----+ voice: {+ mic: 'Talk to your computer. Hold to talk, tap for hands free',+ listening: 'Listening',+ talk: 'Talk, let go to send',+ sending: 'Your computer writes it down',+ waiting: 'LU is answering',+ speaking: 'Reading the answer',+ interrupt: 'Tap to talk',+ end: 'End',+ endName: 'End voice',+ nothingHeard: 'Nothing was heard. Hold the microphone a little longer.',+ micDenied: 'LU has no access to the microphone. Allow it in the system settings.',+ noMic: 'This phone gives LU no microphone.',+ notConnected: 'Connect to your computer to talk to it.',+ gaveUp: 'Hands free ended after a long silence.',+ speakFailed: 'The answer could not be read aloud.',+ },} as constexport type RemoteStatusKey = keyof typeof REMOTE_STRINGS.statusdiff --git a/src/mobile/strings/settings.ts b/src/mobile/strings/settings.tsindex 9da18180..1019bc3a 100644--- a/src/mobile/strings/settings.ts+++ b/src/mobile/strings/settings.ts@@ -507,6 +507,10 @@ export const SETTINGS_STRINGS = {phoneFailed: 'The voice of this phone could not be played. Check the volume and the text to speech settings of this phone.',voiceNeedsCloud: 'Cloud voices need LU Cloud',systemGroup: 'System voice',+ remoteGroup: 'Voice with your computer',+ remoteReadAloud: 'Read the answer aloud',+ remoteReadAloudSub: 'When you speak to LU on your computer, its answer is read aloud. With the voice of this phone, or the voice of the computer when this phone has none.',+ remoteHow: 'In a chat with your computer, hold the microphone to talk and let go to send. Tap it to talk hands free: LU listens, answers and listens again until you tap End. Your computer writes down what you say, nothing goes to LU Cloud.',speed: 'Speed',pitch: 'Pitch',systemVoiceNote: 'Speed and pitch apply to the system voice.',diff --git a/src/mobile/ui/Composer.tsx b/src/mobile/ui/Composer.tsxindex 40622b26..0774052f 100644--- a/src/mobile/ui/Composer.tsx+++ b/src/mobile/ui/Composer.tsx@@ -55,6 +55,11 @@ export interface ComposerProps extends Testable {* take is written down the microphone is busy and takes no tap (mobile round 48).*/dictation?: 'recording' | 'transcribing'+ /**+ * The microphone knows a press and its end (voice over remote, GitHub #212): hold to talk, let go to send, a+ * short tap for hands free. With it the microphone takes no click; Enter or Space on it counts as a tap.+ */+ micHold?: ComposerMicHolddisabled?: boolean/** Prefix for the data-testids of the parts, default "m-chat": m-chat-input, m-chat-send, m-chat-stop, m-chat-mic. */idPrefix?: string@@ -75,6 +80,13 @@ export interface ComposerTune {el?: string}+export interface ComposerMicHold {+ onDown: () => void+ onUp: () => void+ /** Accessible name of the microphone. */+ label?: string+}+export interface ComposerAttach {label: stringonPress: () => void@@ -111,6 +123,45 @@ export function keepFocus(event: { preventDefault: () => void }): void {event.preventDefault()}+/**+ * The handlers of a microphone that knows press and release. The pointer is captured, so a finger that slides off+ * the button while talking still ends the take where it lifts. A click without a pointer (Enter, Space, a screen+ * reader) is a tap. The context menu of a long press is not opened.+ */+/** The microphones a finger is on. On the element, not in the handlers: the composer paints again while a take runs. */+const pressedMics = new WeakSet<Element>()++export function micHoldHandlers(hold: ComposerMicHold) {+ const release = (target: Element) => {+ if (!pressedMics.has(target)) return+ pressedMics.delete(target)+ hold.onUp()+ }+ return {+ onPointerDown: (event: { pointerId: number; button: number; currentTarget: Element; preventDefault: () => void }) => {+ if (event.button !== 0) return+ event.preventDefault()+ try {+ event.currentTarget.setPointerCapture?.(event.pointerId)+ } catch {+ /* a WebView without capture: the release still arrives on the button */+ }+ pressedMics.add(event.currentTarget)+ haptic('light')+ hold.onDown()+ },+ onPointerUp: (event: { currentTarget: Element }) => release(event.currentTarget),+ onPointerCancel: (event: { currentTarget: Element }) => release(event.currentTarget),+ onContextMenu: (event: { preventDefault: () => void }) => event.preventDefault(),+ onClick: (event: { detail: number }) => {+ // detail 0: the keyboard or a screen reader pressed it, no pointer came first.+ if (event.detail !== 0) return+ hold.onDown()+ hold.onUp()+ },+ }+}+export type ComposerSlot = 'stop' | 'send' | 'mic'/** Pure: what the shared slot shows. Empty field: microphone. Text or attachment: Send. Running: Stop. */@@ -131,9 +182,9 @@ export function composerSlot(input: { running?: boolean; text: string; hasAttach* Send is never under the keyboard (ui/room.ts).*/export function Composer(props: ComposerProps) {- const { value, onChange, label = 'Message', placeholder, onSend, running, onStop, onDictate, hasAttachment, sendBlocked, sendLabel = 'Send', status, attachments, tune, attach, action, cloud, replaceField, disabled, idPrefix = 'm-chat', risk, micRisk, dictation } = props+ const { value, onChange, label = 'Message', placeholder, onSend, running, onStop, onDictate, hasAttachment, sendBlocked, sendLabel = 'Send', status, attachments, tune, attach, action, cloud, replaceField, disabled, idPrefix = 'm-chat', risk, micRisk, dictation, micHold } = propsconst ref = useRef<HTMLTextAreaElement>(null)- const slot = composerSlot({ running, text: value, hasAttachment, canDictate: !!onDictate, dictation })+ const slot = composerSlot({ running, text: value, hasAttachment, canDictate: !!onDictate || !!micHold, dictation })const canSend = value.trim().length > 0 || !!hasAttachmentuseEffect(installRoom, [])@@ -211,13 +262,13 @@ export function Composer(props: ComposerProps) {key="mic"type="button"className="m-send m-send--mic"- aria-label="Dictate"+ aria-label={micHold?.label ?? 'Dictate'}aria-busy={dictation === 'transcribing' || undefined}disabled={disabled || dictation === 'transcribing'}data-testid={`${idPrefix}-mic`}data-m-dictation={dictation}{...riskProps(micRisk)}- onClick={onDictate}+ {...(micHold ? micHoldHandlers(micHold) : { onClick: onDictate })}><Icon icon={Mic} /></button>diff --git a/src/mobile/ui/__tests__/composer-mic-hold.dom.test.tsx b/src/mobile/ui/__tests__/composer-mic-hold.dom.test.tsxnew file mode 100644index 00000000..fee58531--- /dev/null+++ b/src/mobile/ui/__tests__/composer-mic-hold.dom.test.tsx@@ -0,0 +1,73 @@+// @vitest-environment jsdom+/**+ * Voice over remote (GitHub #212): the microphone of the composer knows a+ * press and its end. Hold to talk, let go to send; a tap is hands free. A+ * press with the keyboard is a tap.+ *+ * Run: npx vitest run src/mobile/ui/__tests__/composer-mic-hold.dom.test.tsx+ */+import { afterEach, describe, expect, it, vi } from 'vitest'+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { Composer } from '../Composer'++afterEach(cleanup)++function setup() {+ const onDown = vi.fn()+ const onUp = vi.fn()+ render(<Composer value="" onChange={() => {}} onSend={() => {}} micHold={{ onDown, onUp, label: 'Talk to your computer' }} idPrefix="m-remote-chat" />)+ return { onDown, onUp, mic: screen.getByTestId('m-remote-chat-mic') }+}++describe('a microphone that knows press and release', () => {+ it('shows in the slot of an empty field with its own name', () => {+ const { mic } = setup()+ expect(mic.getAttribute('aria-label')).toBe('Talk to your computer')+ })++ it('down starts, up ends, a click after a pointer does nothing more', () => {+ const { onDown, onUp, mic } = setup()+ fireEvent.pointerDown(mic, { button: 0, pointerId: 1 })+ expect(onDown).toHaveBeenCalledTimes(1)+ expect(onUp).not.toHaveBeenCalled()+ fireEvent.pointerUp(mic, { button: 0, pointerId: 1 })+ expect(onUp).toHaveBeenCalledTimes(1)+ fireEvent.click(mic, { detail: 1 })+ expect(onDown).toHaveBeenCalledTimes(1)+ expect(onUp).toHaveBeenCalledTimes(1)+ })++ it('the composer painting again while the finger is down does not lose the release', () => {+ const onDown = vi.fn()+ const onUp = vi.fn()+ const view = (dictation?: 'recording') => <Composer value="" onChange={() => {}} onSend={() => {}} micHold={{ onDown, onUp }} dictation={dictation} replaceField={dictation ? <div /> : undefined} />+ const { rerender } = render(view())+ fireEvent.pointerDown(screen.getByTestId('m-chat-mic'), { button: 0, pointerId: 7 })+ rerender(view('recording'))+ rerender(view('recording'))+ fireEvent.pointerUp(screen.getByTestId('m-chat-mic'), { pointerId: 7 })+ expect(onUp).toHaveBeenCalledTimes(1)+ })++ it('a cancelled pointer ends the take too', () => {+ const { onUp, mic } = setup()+ fireEvent.pointerDown(mic, { button: 0, pointerId: 2 })+ fireEvent.pointerCancel(mic, { pointerId: 2 })+ expect(onUp).toHaveBeenCalledTimes(1)+ })++ it('Enter or Space (a click without a pointer) is a tap', () => {+ const { onDown, onUp, mic } = setup()+ fireEvent.click(mic, { detail: 0 })+ expect(onDown).toHaveBeenCalledTimes(1)+ expect(onUp).toHaveBeenCalledTimes(1)+ })++ it('an up without a down does nothing, and a right click starts nothing', () => {+ const { onDown, onUp, mic } = setup()+ fireEvent.pointerUp(mic, { pointerId: 3 })+ fireEvent.pointerDown(mic, { button: 2, pointerId: 3 })+ expect(onDown).not.toHaveBeenCalled()+ expect(onUp).not.toHaveBeenCalled()+ })+})diff --git a/src/mobile/ui/index.ts b/src/mobile/ui/index.tsindex 7427e7ab..f41d6d1f 100644--- a/src/mobile/ui/index.ts+++ b/src/mobile/ui/index.ts@@ -39,7 +39,7 @@ export { EmptyState, type EmptyStateProps } from './EmptyState'export { Skeleton, SkeletonRows, SkeletonCards } from './Skeleton'export { FitBadge, FIT_TEXT, type FitLevel } from './FitBadge'export { ModelChip, modelChipName, type ModelChipProps } from './ModelChip'-export { Composer, ComposerTuneButton, composerSlot, tuneSummary, type ComposerAttach, type ComposerProps, type ComposerTune } from './Composer'+export { Composer, ComposerTuneButton, composerSlot, micHoldHandlers, tuneSummary, type ComposerAttach, type ComposerMicHold, type ComposerProps, type ComposerTune } from './Composer'export { MediaViewer, type MediaViewerProps } from './MediaViewer'export { MiddleEllipsis, splitMiddle, type MiddleEllipsisProps } from './MiddleEllipsis'export { Block, Hint, Heading, Sparse, Strip, type BlockProps, type StripProps } from './Layout'