rohitsar567 Claude Opus 4.7 (1M context) commited on
Commit
e01547c
·
1 Parent(s): effcfeb

feat(voice): KI-027 — Live is the only voice mode; one-shot PTT pauses it

Browse files

Voice UX simplification per the 2026-05-14 user request. The previous
three-mode setup (push-to-talk button, Hands-free checkbox, Live toggle)
caused the duplicate-mic / duplicate-/api/chat dispatch bug visible in
the user's screenshot, and there was no clear default mode.

Single-mode design:

• Live = ALWAYS ON. The mic is open from the moment the page loads
(auto-enable in a mount effect). There is no longer a "Go Live"
toggle — it's just on. Status pill in the toolbar reads
"Just speak — I'm listening" with a pulsing green dot.

• 🎤 push-to-talk button = momentary suspend. Clicking it calls
live.setLive(false) (which tears down the always-on stream),
waits 120ms for the AudioContext to release the mic, opens a
fresh one-shot recorder, captures with VAD auto-cutoff after 2s
of silence, transcribes + sends, then immediately calls
live.setLive(true) to resume Live. One physical button = one turn.

• Hands-free checkbox: REMOVED. Its "VAD cutoff" semantics are now
the default for PTT; its "auto re-open mic loop" is redundant
with Live; and its presence was confusing.

• Mic permission denied: status pill swaps to "🔇 Mic blocked — use
🎤 to speak, or type below". Textarea + Send + 🎤 button all stay
usable so the user is never stuck.

Empty-state hero now reads "Voice is on. Just start speaking — I'm
listening. Speak over me to interrupt at any time. Prefer to type? Use
the box below." Removes ambiguity for first-time visitors.

Removed code: `handsFree` state, `setHandsFree`, `handsFreeRef`, the
useEffect that toggled mic on/off based on handsFree, the post-TTS
auto-re-open loop in send()'s audio.play() handler, and the
`if (handsFree)` gate inside startRecording (VAD is unconditional now).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>

Files changed (1) hide show
  1. frontend/src/app/page.tsx +75 -79
frontend/src/app/page.tsx CHANGED
@@ -115,10 +115,15 @@ export default function Page() {
115
  }
116
  }, [messages]);
117
  const [uploadStatus, setUploadStatus] = useState<string | null>(null);
118
- const [handsFree, setHandsFree] = useState(false); // VAD auto-cutoff mode
119
- // Live ref of handsFree so async TTS-ended callbacks read the latest value
120
- // (closure captured at audio.play() time would otherwise be stale)
121
- const handsFreeRef = useRef(false);
 
 
 
 
 
122
 
123
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
124
  const audioChunksRef = useRef<Blob[]>([]);
@@ -173,19 +178,16 @@ export default function Page() {
173
  // Hands-free continuous loop: when toggled ON, immediately open mic. When
174
  // toggled OFF, close any in-progress recording. The send() function takes
175
  // care of re-opening the mic after each assistant TTS finishes.
 
 
 
 
 
 
176
  useEffect(() => {
177
- handsFreeRef.current = handsFree;
178
- // KI-026 — when Live mode is active it owns the mic; Hands-free must NOT
179
- // also try to open it. If user enables Hands-free while Live is on, just
180
- // ignore the request.
181
- if (live.live) return;
182
- if (handsFree && !recording && !busy) {
183
- startRecording();
184
- } else if (!handsFree && recording) {
185
- stopRecording();
186
- }
187
  // eslint-disable-next-line react-hooks/exhaustive-deps
188
- }, [handsFree, live.live]);
189
 
190
  function pushUser(text: string) {
191
  setMessages((m) => [...m, { id: `u_${Date.now()}`, role: "user", content: text }]);
@@ -314,24 +316,13 @@ export default function Page() {
314
  });
315
  if (audioUrl) {
316
  const audio = new Audio(audioUrl);
317
- // In hands-free mode, re-open the mic AFTER the assistant's TTS reply
318
- // finishes playing — that's how a Siri/Alexa loop feels natural.
319
- audio.addEventListener("ended", () => {
320
- if (handsFreeRef.current) {
321
- setTimeout(() => { if (handsFreeRef.current) startRecording(); }, 250);
322
- }
323
- });
324
  audio.play().catch(() => {
325
- // Audio playback failed (e.g. browser blocked autoplay) — still
326
- // continue the hands-free loop if enabled.
327
- if (handsFreeRef.current) {
328
- setTimeout(() => { if (handsFreeRef.current) startRecording(); }, 250);
329
- }
330
  });
331
- } else if (handsFreeRef.current) {
332
- // No audio reply (voice toggle off) — restart mic after a short pause
333
- setTimeout(() => { if (handsFreeRef.current) startRecording(); }, 500);
334
  }
 
 
 
335
  } catch (e: unknown) {
336
  const err = e as { name?: string; message?: string };
337
  if (err?.name === "AbortError") {
@@ -409,14 +400,16 @@ export default function Page() {
409
  }, [messages, sessionId, ttsLang, openPolicy, showMarketplace, showProfile, showPremium]);
410
 
411
  async function startRecording() {
412
- // KI-026 (2026-05-14) — voice mode mutual exclusion. If Live mode is
413
- // active it owns the mic + the chat dispatch; the legacy push-to-talk
414
- // and Hands-free paths must NOT run in parallel or we get duplicate
415
- // user transcripts + duplicate /api/chat dispatches + duplicate TTS
416
- // playback (the bug visible in the 2026-05-14 user screenshot).
417
  if (live.live) {
418
- console.warn("[voice] startRecording blocked — Live mode is active");
419
- return;
 
 
 
420
  }
421
  try {
422
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
@@ -430,7 +423,10 @@ export default function Page() {
430
  stream.getTracks().forEach((t) => t.stop());
431
  const blob = new Blob(audioChunksRef.current, { type: recorder.mimeType || "audio/webm" });
432
  setRecording(false);
433
- if (blob.size < 1000) return;
 
 
 
434
  setBusy(true);
435
  try {
436
  const { text } = await postTranscribe(blob, ttsLang);
@@ -438,15 +434,19 @@ export default function Page() {
438
  else pushAssistant("Sorry, I couldn't hear that clearly. Please try again.");
439
  } catch (e: unknown) {
440
  pushAssistant(`Sorry — transcribe error: ${e instanceof Error ? e.message : String(e)}`);
441
- } finally { setBusy(false); }
 
 
 
442
  };
443
  recorder.start();
444
  setRecording(true);
445
 
446
- // Hands-free / VAD auto-cutoff mode: listen for ~1.5s of silence
447
- // (RMS level below threshold) and auto-stop the recording. Falls back
448
- // gracefully if AudioContext unsupported.
449
- if (handsFree) {
 
450
  try {
451
  const AC = window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
452
  const audioCtx = new AC();
@@ -730,11 +730,13 @@ export default function Page() {
730
  <button
731
  type="button"
732
  onClick={recording ? stopRecording : startRecording}
733
- disabled={(busy && !recording) || live.live}
734
  className={`shrink-0 w-11 h-11 rounded-xl flex items-center justify-center transition-all ${
735
  recording ? "bg-[var(--error)] text-white animate-record-pulse" : "bg-[var(--muted)] hover:bg-[var(--border)]"
736
  } disabled:opacity-40`}
737
- title={live.live ? "Live mode is active — voice is handled automatically" : recording ? "Stop recording" : "Voice input"}
 
 
738
  >
739
  {recording ? <StopIcon /> : <MicIcon />}
740
  </button>
@@ -749,40 +751,29 @@ export default function Page() {
749
  </div>
750
  <div className="flex items-center justify-between gap-3 mt-2 pt-2 px-2 text-xs text-[var(--muted-foreground)]">
751
  <div className="flex items-center gap-3">
752
- <label className="flex items-center gap-1.5 cursor-pointer">
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
753
  <input type="checkbox" checked={returnAudio} onChange={(e) => setReturnAudio(e.target.checked)} className="w-3.5 h-3.5 accent-[var(--primary)]" /> Voice reply
754
  </label>
755
- <label
756
- className={`flex items-center gap-1.5 ${live.live ? "opacity-40 cursor-not-allowed" : "cursor-pointer"}`}
757
- title={live.live ? "Disabled — Live mode is on. Turn off Live to use Hands-free." : "Hands-free voice — auto-submits when you stop speaking"}
758
- >
759
- <input
760
- type="checkbox"
761
- checked={handsFree && !live.live}
762
- disabled={live.live}
763
- onChange={(e) => setHandsFree(e.target.checked)}
764
- className="w-3.5 h-3.5 accent-[var(--primary)]"
765
- /> Hands-free
766
- </label>
767
- {/* Live conversation — full-duplex with VAD barge-in. Speak any
768
- time, even while the bot is still talking, and it stops mid-
769
- sentence and listens to you. No button press needed. */}
770
- <button
771
- type="button"
772
- onClick={() => live.setLive(!live.live)}
773
- className={`flex items-center gap-1.5 px-2 py-0.5 rounded-full border text-xs font-medium transition ${
774
- live.live
775
- ? "bg-red-500/15 border-red-400 text-red-600"
776
- : "border-[var(--border)] hover:border-[var(--primary)] hover:text-[var(--primary)]"
777
- }`}
778
- title="Live conversation: continuous mic, interrupt the bot by speaking"
779
- >
780
- <span className={`inline-block w-2 h-2 rounded-full ${live.live ? (live.recording ? "bg-red-500 animate-pulse" : "bg-green-500 animate-pulse") : "bg-gray-400"}`} />
781
- {live.live ? (live.recording ? "Listening…" : "Live ✓") : "Go Live"}
782
- </button>
783
- {live.micPermissionDenied && (
784
- <span className="text-red-500" title="Browser blocked microphone access — check site permissions">mic blocked</span>
785
- )}
786
  <label className="flex items-center gap-1.5">
787
  Lang:
788
  <select value={ttsLang} onChange={(e) => setTtsLang(e.target.value as "en-IN" | "hi-IN")} className="bg-transparent border border-[var(--border)] rounded px-1.5 py-0.5">
@@ -791,7 +782,7 @@ export default function Page() {
791
  </select>
792
  </label>
793
  </div>
794
- <div className="hidden sm:block">Enter to send · 📎 to upload your own PDF</div>
795
  </div>
796
  </div>
797
  </main>
@@ -1302,10 +1293,15 @@ function EmptyState({ onSuggest, coverage, t }: { onSuggest: (q: string) => void
1302
  {t("welcome.coverage_template", { policies: coverage.total_policies, insurers: coverage.total_insurers })}
1303
  </p>
1304
  )}
1305
- <div className="bg-[var(--accent)] border border-[var(--primary)] rounded-xl px-4 py-3 max-w-xl mb-6 text-left">
1306
  <div className="text-xs font-semibold text-[var(--primary)] mb-1">{t("welcome.trust_title")}</div>
1307
  <p className="text-xs text-[var(--muted-foreground)] leading-snug">{t("welcome.trust_body")}</p>
1308
  </div>
 
 
 
 
 
1309
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 w-full max-w-2xl">
1310
  {suggested.map((key, i) => {
1311
  const q = t(key);
 
115
  }
116
  }, [messages]);
117
  const [uploadStatus, setUploadStatus] = useState<string | null>(null);
118
+ // KI-027 (2026-05-14) — voice UX simplification. The legacy `handsFree`
119
+ // mode (its own VAD auto-cutoff + post-turn mic re-open loop) has been
120
+ // removed. We now have exactly two voice paths, mutually exclusive:
121
+ // • Live ✓ — full-duplex with barge-in (the default, owned by
122
+ // useLiveConversation).
123
+ // • 🎤 push-to-talk — click to start, VAD auto-stops on 2s silence,
124
+ // submits, mic closes. One utterance per click.
125
+ // The "Hands-free continuous loop" was the source of the duplicate-mic
126
+ // bug in the 2026-05-14 user screenshot and added zero value over Live.
127
 
128
  const mediaRecorderRef = useRef<MediaRecorder | null>(null);
129
  const audioChunksRef = useRef<Blob[]>([]);
 
178
  // Hands-free continuous loop: when toggled ON, immediately open mic. When
179
  // toggled OFF, close any in-progress recording. The send() function takes
180
  // care of re-opening the mic after each assistant TTS finishes.
181
+ // KI-027 — Live mode is the SOLE voice mode. Always on (no toggle off).
182
+ // The only thing that suspends it is an explicit press of the 🎤
183
+ // push-to-talk button — and even then, Live resumes immediately after
184
+ // the one-shot PTT recording finishes. If mic permission is denied,
185
+ // useLiveConversation flips micPermissionDenied=true and the UI shows a
186
+ // "mic blocked — type to chat" hint; the textarea + Send still work.
187
  useEffect(() => {
188
+ live.setLive(true);
 
 
 
 
 
 
 
 
 
189
  // eslint-disable-next-line react-hooks/exhaustive-deps
190
+ }, []);
191
 
192
  function pushUser(text: string) {
193
  setMessages((m) => [...m, { id: `u_${Date.now()}`, role: "user", content: text }]);
 
316
  });
317
  if (audioUrl) {
318
  const audio = new Audio(audioUrl);
 
 
 
 
 
 
 
319
  audio.play().catch(() => {
320
+ /* autoplay blocked — user can click the inline audio player to hear it */
 
 
 
 
321
  });
 
 
 
322
  }
323
+ // KI-027 — Hands-free auto-reopen loop removed. Live mode provides the
324
+ // continuous-conversation behavior; push-to-talk is now strictly
325
+ // one-shot per click.
326
  } catch (e: unknown) {
327
  const err = e as { name?: string; message?: string };
328
  if (err?.name === "AbortError") {
 
400
  }, [messages, sessionId, ttsLang, openPolicy, showMarketplace, showProfile, showPremium]);
401
 
402
  async function startRecording() {
403
+ // KI-027 — Push-to-talk briefly SUSPENDS Live mode (which is otherwise
404
+ // always on). This avoids the duplicate-mic / duplicate-/api/chat bug
405
+ // from the 2026-05-14 screenshot: only one path captures + dispatches
406
+ // any given utterance. Live resumes when PTT finishes (recorder.onstop).
 
407
  if (live.live) {
408
+ live.setLive(false);
409
+ // Small wait so useLiveConversation tears down its stream before we
410
+ // open a fresh one; without this, two AudioContexts can briefly grab
411
+ // the same input device.
412
+ await new Promise((r) => setTimeout(r, 120));
413
  }
414
  try {
415
  const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
 
423
  stream.getTracks().forEach((t) => t.stop());
424
  const blob = new Blob(audioChunksRef.current, { type: recorder.mimeType || "audio/webm" });
425
  setRecording(false);
426
+ // KI-027 — PTT done: resume Live mode so the user goes right back to
427
+ // hands-free conversation without a button press.
428
+ const resumeLive = () => { live.setLive(true); };
429
+ if (blob.size < 1000) { resumeLive(); return; }
430
  setBusy(true);
431
  try {
432
  const { text } = await postTranscribe(blob, ttsLang);
 
434
  else pushAssistant("Sorry, I couldn't hear that clearly. Please try again.");
435
  } catch (e: unknown) {
436
  pushAssistant(`Sorry — transcribe error: ${e instanceof Error ? e.message : String(e)}`);
437
+ } finally {
438
+ setBusy(false);
439
+ resumeLive();
440
+ }
441
  };
442
  recorder.start();
443
  setRecording(true);
444
 
445
+ // KI-027 — VAD auto-cutoff is now ALWAYS on for the push-to-talk
446
+ // fallback. Click the mic, talk, and the recording auto-stops after
447
+ // ~2s of silence. Was previously gated behind `handsFree` which we
448
+ // removed. Push-to-talk is one-shot per click — no auto re-open.
449
+ if (true) {
450
  try {
451
  const AC = window.AudioContext || (window as unknown as { webkitAudioContext: typeof AudioContext }).webkitAudioContext;
452
  const audioCtx = new AC();
 
730
  <button
731
  type="button"
732
  onClick={recording ? stopRecording : startRecording}
733
+ disabled={busy && !recording}
734
  className={`shrink-0 w-11 h-11 rounded-xl flex items-center justify-center transition-all ${
735
  recording ? "bg-[var(--error)] text-white animate-record-pulse" : "bg-[var(--muted)] hover:bg-[var(--border)]"
736
  } disabled:opacity-40`}
737
+ title={recording
738
+ ? "Push-to-talk: recording… click to stop or stay silent for 2s"
739
+ : "Push-to-talk (pauses always-on listening for one turn)"}
740
  >
741
  {recording ? <StopIcon /> : <MicIcon />}
742
  </button>
 
751
  </div>
752
  <div className="flex items-center justify-between gap-3 mt-2 pt-2 px-2 text-xs text-[var(--muted-foreground)]">
753
  <div className="flex items-center gap-3">
754
+ {/* KI-027 — Live mode is the default + only voice mode. This is
755
+ a STATUS pill, not a toggle. The only way to "pause" Live is
756
+ to press the 🎤 push-to-talk button for one turn. */}
757
+ {!live.micPermissionDenied ? (
758
+ <span
759
+ className="flex items-center gap-1.5 px-2 py-0.5 rounded-full border border-[var(--border)] text-xs font-medium text-[var(--muted-foreground)]"
760
+ title={live.live
761
+ ? "Always-on voice. Just speak — I'm listening. Speak over me to interrupt at any time."
762
+ : "Voice paused for push-to-talk; resumes after this turn."}
763
+ >
764
+ <span className={`inline-block w-2 h-2 rounded-full ${
765
+ live.live ? (live.recording ? "bg-red-500 animate-pulse" : "bg-emerald-500 animate-pulse") : "bg-gray-400"
766
+ }`} />
767
+ {live.live ? (live.recording ? "Listening…" : "Just speak — I'm listening") : "Push-to-talk active"}
768
+ </span>
769
+ ) : (
770
+ <span className="text-rose-500 text-xs" title="Allow mic in your browser site settings, or use the 🎤 push-to-talk button">
771
+ 🔇 Mic blocked — use 🎤 to speak, or type below
772
+ </span>
773
+ )}
774
+ <label className="flex items-center gap-1.5 cursor-pointer" title="Bot replies with both text and audio">
775
  <input type="checkbox" checked={returnAudio} onChange={(e) => setReturnAudio(e.target.checked)} className="w-3.5 h-3.5 accent-[var(--primary)]" /> Voice reply
776
  </label>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
777
  <label className="flex items-center gap-1.5">
778
  Lang:
779
  <select value={ttsLang} onChange={(e) => setTtsLang(e.target.value as "en-IN" | "hi-IN")} className="bg-transparent border border-[var(--border)] rounded px-1.5 py-0.5">
 
782
  </select>
783
  </label>
784
  </div>
785
+ <div className="hidden sm:block">Enter to send · 🎤 to push-to-talk · 📎 PDF</div>
786
  </div>
787
  </div>
788
  </main>
 
1293
  {t("welcome.coverage_template", { policies: coverage.total_policies, insurers: coverage.total_insurers })}
1294
  </p>
1295
  )}
1296
+ <div className="bg-[var(--accent)] border border-[var(--primary)] rounded-xl px-4 py-3 max-w-xl mb-4 text-left">
1297
  <div className="text-xs font-semibold text-[var(--primary)] mb-1">{t("welcome.trust_title")}</div>
1298
  <p className="text-xs text-[var(--muted-foreground)] leading-snug">{t("welcome.trust_body")}</p>
1299
  </div>
1300
+ {/* KI-027 — make it obvious that voice is always-on. */}
1301
+ <div className="flex items-center gap-2 max-w-xl mb-6 text-sm text-[var(--muted-foreground)]">
1302
+ <span className="inline-block w-2.5 h-2.5 rounded-full bg-emerald-500 animate-pulse" />
1303
+ <span><strong className="text-[var(--foreground)]">Voice is on.</strong> Just start speaking — I&apos;m listening. Speak over me to interrupt at any time. Prefer to type? Use the box below.</span>
1304
+ </div>
1305
  <div className="grid grid-cols-1 sm:grid-cols-2 gap-2 w-full max-w-2xl">
1306
  {suggested.map((key, i) => {
1307
  const q = t(key);