Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Dictation: mic button in the message box (frontend for #610) (#623)
Oleksandr Ivanchenko129739e6bd86
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex cdc3bfe3..f252d218 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -1,4 +1,5 @@import React, { Suspense, lazy, useState, useEffect, useRef, useCallback, useMemo } from 'react';+import { refreshDictation } from './dictation';import { DecidingMap, applyDecideEvent, decisionsApi, hydrateDeciding } from './decideFirst';import { Sidebar, Kwant, Channel, Team, memberIdsOf } from './components/Sidebar';import { SpaceSettings, SpaceSettingsTab } from './components/SpaceSettings';@@ -467,6 +468,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({setSpaceSettingsTab(null);setSettingsFocusRow(null);setSettingsClosedCount((n) => n + 1);+ // A key may have been added or removed: the dictation mic asks again.+ refreshDictation();// Accounts may have changed: the getting-started list counts the ready ones.onSpacesChanged();};@@ -4209,6 +4212,8 @@ export const SpaceApp: React.FC<SpaceAppProps> = ({const inbox = <InboxPage tab={inboxTab} onTab={setInboxTab} count={inboxCount} onBack={backToList} newPage={away} loosePage={loose} />;const chat = (<ChatView+ spaceId={space.id}+ onToast={pushToast}heldNotes={heldNotes}dropOff={!!spaceSettingsTab}title={chatTitle}diff --git a/frontend/src/components/ChatView.tsx b/frontend/src/components/ChatView.tsxindex 5772f7ff..a2a4b3d0 100644--- a/frontend/src/components/ChatView.tsx+++ b/frontend/src/components/ChatView.tsx@@ -110,6 +110,7 @@ import { liveBubble, waitingOn } from '../workingStrip';import { COMPOSE_PREFILL_EVENT, withPrefill } from './results/SmartResult';import { FilesPreviewOnly } from './results/Files';import { ReactionButtons, ReplyButton, ReplyChip, ReplyQuote } from './MessageReactions';+import { DictationAnnouncer, DictationLine, DictationSetupPopover, MicButton, useDictation } from './DictationMic';import { ReactResult, Reaction, ReplyRef, botNameOf, excerptOf, questionMessageId, reactionOf, replyRefOf } from '../reactReply';export interface ChatMessage {@@ -346,6 +347,10 @@ export interface ChatViewProps {onSendToOtherBot?: (question: ChatMessage, kwantId: string) => Promise<string | void>;/** Opens Space settings → Accounts; turns a "nothing can run" reply into a card with a button. */onOpenAccounts?: () => void;+ /** The space's real id (spc_…): the dictation mic asks it whether it can turn speech into text. */+ spaceId?: string;+ /** A short notice at the corner of the window (dictation stopped because you left the chat). */+ onToast?: (title: string, detail?: string) => void;/** Opens Settings › All spaces › Usage at the daily spending stop. */onOpenUsage?: () => void;/** Opens App settings at the Computer card, "Run Claude inside the VM" focused (isolation notices). */@@ -575,6 +580,8 @@ export const ChatView: React.FC<ChatViewProps> = ({rerouteTargets = [],onSendToOtherBot,onOpenAccounts,+ spaceId,+ onToast,onOpenUsage,onOpenComputerSettings,budgetBotId = null,@@ -644,6 +651,18 @@ export const ChatView: React.FC<ChatViewProps> = ({const [copiedId, setCopiedId] = useState<string | null>(null);const scrollRef = useRef<HTMLDivElement>(null);const textareaRef = useRef<HTMLTextAreaElement>(null);+ // Dictation (design.md): the mic between @ and Send; one line at the top of the box says what's happening.+ const reducedMotion = useMedia('(prefers-reduced-motion: reduce)');+ const dict = useDictation({+ spaceId,+ chatKey: contextKey,+ phone,+ touch,+ value: inputVal,+ textareaRef,+ setValue: setInputVal,+ onToast: onToast ? (t) => onToast(t) : undefined,+ });const handleInsertTag = (tag: string) => {playSfx('click');@@ -1208,13 +1227,16 @@ export const ChatView: React.FC<ChatViewProps> = ({});};- const canSend = ideaMode ? !ideaBlocked : composerReady(inputVal, uploads);+ // Send waits for dictation to finish, like it waits for uploads.+ const canSend = !dict.busy && (ideaMode ? !ideaBlocked : composerReady(inputVal, uploads));// The line under the field: too long or a file shows at once; an empty idea only once Enter was tried.const ideaLine = (ideaError && ideaError.text === inputVal ? ideaError.line : null) ?? (ideaBlocked && (ideaTried || ideaLength(inputVal) > 0 || uploads.length > 0) ? ideaBlocked : null);const stillUploading = uploads.some((u) => u.state === 'uploading');const handleSubmit = (e?: React.FormEvent) => {if (e) e.preventDefault();+ if (dict.busy) return;+ dict.noteSent();// A reply in progress doesn't block the next message (it waits its turn); a team discussion does.if (ideaMode) {// Ideas never wait on a reply or a discussion: the jar is not a bot.@@ -2007,7 +2029,11 @@ export const ChatView: React.FC<ChatViewProps> = ({const showAnswers = !ideaMode && (!phone || home?.kind !== 'bot' || target.kind === 'mention');const showHintText = !(phone && touch);const measure16 = (t: string) => measureText16(t, textareaRef.current ? getComputedStyle(textareaRef.current).fontFamily : '');- const placeholder = changeFor && replyTo ? changePlaceholder(changeFor) : askOnly+ const placeholder = dict.phase === 'recording' && !inputVal+ ? 'Speak now…'+ : changeFor && replyTo+ ? changePlaceholder(changeFor)+ : askOnly? phone? fitPlaceholder(answerPlaceholder(awaitingBot?.name || streamingSpeakerName || title), 'Your answer…', fieldWidth, measure16): answerPlaceholder(awaitingBot?.name || streamingSpeakerName || title)@@ -2649,6 +2675,9 @@ export const ChatView: React.FC<ChatViewProps> = ({onSelect={handleSelectMention}/>)}+ <DictationSetupPopover d={dict} phone={phone} onOpenAccounts={onOpenAccounts} />+ <DictationLine d={dict} phone={phone} botName={title} reduced={reducedMotion} />+ <DictationAnnouncer d={dict} /><textarearef={textareaRef}@@ -2667,6 +2696,7 @@ export const ChatView: React.FC<ChatViewProps> = ({onChange={(e) => {const val = e.target.value;setInputVal(val);+ dict.noteTyping();e.target.style.height = 'auto';e.target.style.height = `${Math.min(e.target.scrollHeight, 160)}px`;checkMention(val, e.target.selectionStart);@@ -2734,7 +2764,7 @@ export const ChatView: React.FC<ChatViewProps> = ({<AtSign size={phone ? 18 : 17} aria-hidden="true" />{/* Phone (spec A5): "New" anchors to the @ button's own box, never on the field's border or an Ask chip */}{phone && !isStreaming && (- <NewTag id="mention" className={`absolute -top-1.5 -right-1 ${isMentionOpen ? 'hidden' : ''} ${layerPhase || budgetBanner ? 'hidden' : ''}`} />+ <NewTag id="mention" className={`absolute -top-1.5 -right-1 ${isMentionOpen ? 'hidden' : ''} ${dict.popOpen ? 'hidden' : ''} ${layerPhase || budgetBanner ? 'hidden' : ''}`} />)}</button>{stacked && <span className="flex-1" aria-hidden="true" />}@@ -2747,8 +2777,8 @@ export const ChatView: React.FC<ChatViewProps> = ({{!phone && !isStreaming && (<NewTagid="mention"- className={`absolute bottom-full mb-1.5 [--kw-cbtn-step:50px] sm:[--kw-cbtn-step:42px] ${isMentionOpen ? 'hidden' : ''} ${layerPhase || budgetBanner ? 'hidden' : ''}`}- style={{ right: 'calc(11px + var(--kw-cbtn-step))' }}+ className={`absolute bottom-full mb-1.5 [--kw-cbtn-step:50px] sm:[--kw-cbtn-step:42px] ${isMentionOpen ? 'hidden' : ''} ${dict.popOpen ? 'hidden' : ''} ${layerPhase || budgetBanner ? 'hidden' : ''}`}+ style={{ right: dict.view === 'hidden' ? 'calc(11px + var(--kw-cbtn-step))' : 'calc(11px + 2 * var(--kw-cbtn-step))' }}/>)}@@ -2772,6 +2802,7 @@ export const ChatView: React.FC<ChatViewProps> = ({{ideaLength(inputVal).toLocaleString('en-US')} / {IDEA_MAX.toLocaleString('en-US')}</span>)}+ <MicButton d={dict} phone={phone} />{ideaMode ? (<buttontype="submit"@@ -2788,14 +2819,14 @@ export const ChatView: React.FC<ChatViewProps> = ({><JarIcon size={phone ? 18 : 17} /></button>- ) : (askOnly || !(isStreaming && (discussionState?.inProgress || !canSend))) && (+ ) : !(phone && !stacked && dict.view !== 'hidden') && (askOnly || !(isStreaming && (discussionState?.inProgress || (!canSend && !dict.busy)))) && (<buttontype="submit"- aria-label={stillUploading ? 'Send (waiting for uploads)' : askOnly ? 'Send (answers the question)' : isStreaming ? 'Send (waits for the current reply)' : 'Send'}- title={stillUploading ? 'Waiting for uploads to finish' : undefined}+ aria-label={dict.busy ? 'Send (waiting for dictation)' : stillUploading ? 'Send (waiting for uploads)' : askOnly ? 'Send (answers the question)' : isStreaming ? 'Send (waits for the current reply)' : 'Send'}+ title={dict.busy ? 'Waiting for dictation to finish' : stillUploading ? 'Waiting for uploads to finish' : undefined}disabled={!canSend}data-send-ready={canSend ? 'true' : 'false'}- className={`${phone ? 'w-11 h-11 focus-visible:outline-[#b8adff]' : 'w-11 h-11 sm:w-9 sm:h-9 focus-visible:outline-sky-300'} rounded-xl flex items-center justify-center flex-shrink-0 transition-[transform,filter,box-shadow,background-color] duration-150 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 ${+ className={`${phone ? 'w-11 h-11 ml-1.5 focus-visible:outline-[#b8adff]' : 'w-11 h-11 sm:w-9 sm:h-9 focus-visible:outline-sky-300'} rounded-xl flex items-center justify-center flex-shrink-0 transition-[transform,filter,box-shadow,background-color] duration-150 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 ${canSend? phone? 'bg-[#6c58e0] text-white hover:bg-[#5845bd] active:scale-95 motion-reduce:transition-none motion-reduce:active:scale-100'diff --git a/frontend/src/components/DictationMic.tsx b/frontend/src/components/DictationMic.tsxnew file mode 100644index 00000000..f37ad350--- /dev/null+++ b/frontend/src/components/DictationMic.tsx@@ -0,0 +1,828 @@+// The dictation mic in the message box (Mira, autonomy/dictation/design.md): the hook that records and+// turns speech into text, the mic button, the one dictation line inside the box, and the "isn't set up"+// popover. The server does the speech work (#610); nothing goes to a bot before Send.+import { useCallback, useEffect, useReducer, useRef, useState, type RefObject } from 'react';+import { AlertCircle, Check, Loader2, Mic, MicOff, RotateCcw, Square, Undo2, X } from 'lucide-react';+import {+ ADDED_MS,+ HIDDEN_MS,+ INSECURE_WHY,+ MAX_SECONDS,+ NO_WORDS,+ SILENCE_LEVEL,+ SILENCE_MS,+ WARN_SECONDS,+ barScales,+ browserSupports,+ cachedAvailability,+ canRetry,+ clock,+ getAvailability,+ insertDictated,+ langHint,+ micErrorText,+ micHidden,+ micVisible,+ onDictationChange,+ rmsLevel,+ setAvailability,+ setMicHidden,+ transcribe,+ undoDictated,+ wordCount,+ wordsLabel,+ type Inserted,+ type MicView,+} from '../dictation';++export type DictPhase = 'idle' | 'asking' | 'recording' | 'transcribing';++export type DictLine =+ | { kind: 'asking' }+ | { kind: 'recording' }+ | { kind: 'transcribing'; seconds: number }+ | { kind: 'added'; words: number; ins: Inserted }+ | { kind: 'bad'; text: string; retry: boolean }+ | { kind: 'warn'; text: string };++export interface DictationOptions {+ spaceId?: string | null;+ /** The open chat; a change stops and discards a recording. */+ chatKey?: string;+ phone: boolean;+ touch: boolean;+ /** The box's text now. */+ value: string;+ textareaRef: RefObject<HTMLTextAreaElement>;+ setValue: (v: string) => void;+ onToast?: (title: string) => void;+}++export interface Dictation {+ view: MicView;+ phase: DictPhase;+ /** Recording or turning into text: Send waits. */+ busy: boolean;+ line: DictLine | null;+ canUndo: boolean;+ silent: boolean;+ startedAt: number;+ levelRef: RefObject<number>;+ secure: boolean;+ why: string | null;+ popOpen: boolean;+ announce: { text: string; n: number };+ micRef: RefObject<HTMLButtonElement>;+ popRef: RefObject<HTMLDivElement>;+ toggle: () => void;+ cancel: () => void;+ retry: () => void;+ dismiss: () => void;+ undo: () => void;+ closePopover: (focusMic?: boolean) => void;+ hideMic: () => void;+ /** A keystroke in the box: the "Added" line goes. */+ noteTyping: () => void;+ /** Sent: the "Added" line goes. */+ noteSent: () => void;+}++interface Rec {+ stream: MediaStream;+ recorder: MediaRecorder;+ chunks: Blob[];+ ctx: AudioContext | null;+ raf: number;+ cap: ReturnType<typeof setTimeout>;+ startedAt: number;+}++const supportedNow = () => (typeof window === 'undefined' ? false : browserSupports(window as unknown as Parameters<typeof browserSupports>[0]));+const secureNow = () => typeof window === 'undefined' || window.isSecureContext !== false;++export function useDictation(o: DictationOptions): Dictation {+ const { spaceId, chatKey, phone, touch, value, textareaRef, setValue, onToast } = o;+ const [, bump] = useReducer((x: number) => x + 1, 0);+ const [phase, setPhaseState] = useState<DictPhase>('idle');+ const [line, setLine] = useState<DictLine | null>(null);+ const [silent, setSilent] = useState(false);+ const [startedAt, setStartedAt] = useState(0);+ const [popOpen, setPopOpen] = useState(false);+ const [announce, setAnnounceState] = useState({ text: '', n: 0 });+ const micRef = useRef<HTMLButtonElement>(null);+ const popRef = useRef<HTMLDivElement>(null);+ const levelRef = useRef(0);+ const recRef = useRef<Rec | null>(null);+ const abortRef = useRef<AbortController | null>(null);+ const blobRef = useRef<{ blob: Blob; seconds: number } | null>(null);+ const insertAtRef = useRef(0);+ const genRef = useRef(0);+ const phaseRef = useRef<DictPhase>('idle');+ const addedTimer = useRef<ReturnType<typeof setTimeout> | null>(null);+ const valueRef = useRef(value);+ valueRef.current = value;+ const touchedRef = useRef(false);+ const live = useRef({ spaceId, phone, touch, setValue, onToast });+ live.current = { spaceId, phone, touch, setValue, onToast };++ const setPhase = (p: DictPhase) => {+ phaseRef.current = p;+ setPhaseState(p);+ };+ const say = (text: string) => setAnnounceState((a) => ({ text, n: a.n + 1 }));+ const focusMic = () => setTimeout(() => micRef.current?.focus({ preventScroll: true }), 0);+ const clearAdded = () => {+ if (addedTimer.current) clearTimeout(addedTimer.current);+ addedTimer.current = null;+ };++ // Availability: asked when the box mounts or the space changes, and again when the window gets focus.+ useEffect(() => onDictationChange(bump), []);+ useEffect(() => {+ if (!spaceId) return;+ void getAvailability(spaceId);+ const onFocus = () => void getAvailability(spaceId, { fresh: true });+ window.addEventListener('focus', onFocus);+ return () => window.removeEventListener('focus', onFocus);+ }, [spaceId]);++ // Where the words go: the caret, if the box ever had it; else the end.+ useEffect(() => {+ const ta = textareaRef.current;+ if (!ta) return;+ const on = () => {+ touchedRef.current = true;+ };+ ta.addEventListener('focus', on);+ return () => ta.removeEventListener('focus', on);+ }, [textareaRef]);++ const supported = supportedNow();+ const secure = secureNow();+ const avail = spaceId ? cachedAvailability(spaceId) : undefined;+ const view: MicView = spaceId ? micVisible({ supported, secure, availability: avail, hidden: micHidden(spaceId) }) : 'hidden';+ const why = !secure ? INSECURE_WHY : avail && avail !== 'error' ? avail.why ?? 'Add an OpenAI API key in Apps & accounts to dictate.' : null;++ /** Stops the microphone and the meter. `keep`: hand the recording on; else throw it away. */+ const stopRec = (keep: boolean) => {+ const r = recRef.current;+ if (!r) return;+ recRef.current = null;+ clearTimeout(r.cap);+ cancelAnimationFrame(r.raf);+ void r.ctx?.close().catch(() => {});+ const seconds = Math.max(0, (Date.now() - r.startedAt) / 1000);+ const finish = () => {+ const type = r.recorder.mimeType || r.chunks[0]?.type || 'audio/webm';+ void send(new Blob(r.chunks, { type }), seconds);+ };+ if (keep) r.recorder.onstop = finish;+ else r.recorder.onstop = null;+ let stopped = false;+ try {+ if (r.recorder.state !== 'inactive') {+ r.recorder.stop();+ stopped = true;+ }+ } catch {+ /* already stopped */+ }+ r.stream.getTracks().forEach((t) => t.stop());+ setSilent(false);+ levelRef.current = 0;+ if (keep) {+ setPhase('transcribing');+ setLine({ kind: 'transcribing', seconds });+ say('Turning speech into text.');+ if (!stopped) finish();+ }+ };++ const send = async (blob: Blob, seconds: number) => {+ const sid = live.current.spaceId;+ if (!sid) return;+ blobRef.current = { blob, seconds };+ abortRef.current?.abort();+ const abort = new AbortController();+ abortRef.current = abort;+ setPhase('transcribing');+ setLine({ kind: 'transcribing', seconds });+ let r;+ try {+ r = await transcribe(sid, blob, langHint(typeof navigator === 'undefined' ? null : navigator.language), abort.signal);+ } catch {+ return; // cancelled+ }+ if (abortRef.current !== abort) return;+ abortRef.current = null;+ setPhase('idle');+ if (r.ok) {+ const text = r.text.trim();+ blobRef.current = null;+ if (!text) {+ setLine({ kind: 'warn', text: NO_WORDS });+ say(NO_WORDS);+ focusMic();+ return;+ }+ const ins = insertDictated(valueRef.current, insertAtRef.current, text);+ valueRef.current = ins.value;+ live.current.setValue(ins.value);+ const n = wordCount(text);+ setLine({ kind: 'added', words: n, ins });+ say(`Added ${wordsLabel(n)} to the message.`);+ clearAdded();+ addedTimer.current = setTimeout(() => setLine((l) => (l?.kind === 'added' ? null : l)), ADDED_MS);+ const handTouch = live.current.phone && live.current.touch;+ setTimeout(() => {+ const ta = textareaRef.current;+ if (ta) {+ ta.style.height = 'auto';+ ta.style.height = `${Math.min(ta.scrollHeight, 160)}px`;+ }+ if (handTouch || !ta) micRef.current?.focus({ preventScroll: true });+ else {+ ta.focus();+ ta.setSelectionRange(ins.caret, ins.caret);+ }+ }, 0);+ return;+ }+ if (r.status === 409 && r.code === 'no_transcriber') {+ blobRef.current = null;+ setAvailability(sid, { available: false, source: null, why: r.why ?? r.error });+ setLine(null);+ setPopOpen(true);+ return;+ }+ const retry = canRetry(r.status, r.code);+ if (!retry) blobRef.current = null;+ setLine({ kind: 'bad', text: r.error, retry });+ focusMic();+ };++ const start = async () => {+ const sid = live.current.spaceId;+ if (!sid) return;+ clearAdded();+ blobRef.current = null;+ const ta = textareaRef.current;+ const v = valueRef.current;+ insertAtRef.current = ta && touchedRef.current ? Math.min(ta.selectionEnd ?? v.length, v.length) : v.length;+ const gen = ++genRef.current;+ setPhase('asking');+ setLine({ kind: 'asking' });+ let stream: MediaStream;+ try {+ stream = await navigator.mediaDevices.getUserMedia({ audio: true });+ } catch (err) {+ if (gen !== genRef.current) return;+ setPhase('idle');+ const text = micErrorText((err as { name?: string })?.name, live.current.phone);+ setLine({ kind: 'warn', text });+ focusMic();+ return;+ }+ if (gen !== genRef.current) {+ stream.getTracks().forEach((t) => t.stop());+ return;+ }+ let recorder: MediaRecorder;+ try {+ recorder = new MediaRecorder(stream);+ } catch {+ stream.getTracks().forEach((t) => t.stop());+ setPhase('idle');+ setLine({ kind: 'warn', text: micErrorText('', live.current.phone) });+ focusMic();+ return;+ }+ const chunks: Blob[] = [];+ recorder.ondataavailable = (e) => {+ if (e.data && e.data.size > 0) chunks.push(e.data);+ };+ const now = Date.now();+ const rec: Rec = { stream, recorder, chunks, ctx: null, raf: 0, cap: setTimeout(() => stopRec(true), MAX_SECONDS * 1000), startedAt: now };+ recRef.current = rec;+ // The device going away (unplugged) stops and keeps what's there.+ stream.getAudioTracks().forEach((t) => t.addEventListener('ended', () => recRef.current === rec && stopRec(true)));+ // The level meter and the silence hint, at about 15 fps.+ try {+ const AC: typeof AudioContext | undefined = window.AudioContext ?? (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;+ if (AC) {+ const ctx = new AC();+ const an = ctx.createAnalyser();+ an.fftSize = 1024;+ ctx.createMediaStreamSource(stream).connect(an);+ rec.ctx = ctx;+ const buf = new Float32Array(an.fftSize);+ let last = 0;+ let lastSound = now;+ let quiet = false;+ const tick = (t: number) => {+ if (recRef.current !== rec) return;+ if (t - last >= 66) {+ last = t;+ an.getFloatTimeDomainData(buf);+ const lvl = rmsLevel(buf);+ levelRef.current = lvl;+ const at = Date.now();+ if (lvl >= SILENCE_LEVEL) lastSound = at;+ const q = at - lastSound > SILENCE_MS;+ if (q !== quiet) {+ quiet = q;+ setSilent(q);+ }+ }+ rec.raf = requestAnimationFrame(tick);+ };+ rec.raf = requestAnimationFrame(tick);+ }+ } catch {+ /* no meter: the timer still says it's working */+ }+ recorder.start(1000);+ setStartedAt(now);+ setSilent(false);+ setPhase('recording');+ setLine({ kind: 'recording' });+ say('Listening. Press the mic or Escape to stop.');+ };++ /** Everything stops and nothing is kept (Cancel, chat change, hidden tab). */+ const discard = () => {+ genRef.current++;+ const was = phaseRef.current;+ stopRec(false);+ abortRef.current?.abort();+ abortRef.current = null;+ blobRef.current = null;+ setPhase('idle');+ setLine(null);+ setSilent(false);+ return was;+ };++ const toggle = () => {+ const p = phaseRef.current;+ if (p === 'transcribing' || p === 'asking') return;+ if (p === 'recording') return stopRec(true);+ if (view === 'muted') {+ setPopOpen((x) => !x);+ return;+ }+ if (view === 'ready') void start();+ };++ const cancel = () => {+ discard();+ say('Dictation cancelled.');+ micRef.current?.focus({ preventScroll: true });+ };++ const retry = () => {+ const b = blobRef.current;+ if (b) void send(b.blob, b.seconds);+ };++ const dismiss = () => {+ clearAdded();+ blobRef.current = null;+ setLine(null);+ micRef.current?.focus({ preventScroll: true });+ };++ const canUndo = line?.kind === 'added' && undoDictated(value, line.ins) !== null;+ const undo = () => {+ if (line?.kind !== 'added') return;+ const next = undoDictated(valueRef.current, line.ins);+ if (next === null) return;+ clearAdded();+ valueRef.current = next;+ setValue(next);+ setLine(null);+ say('Dictated words removed.');+ const at = line.ins.from;+ setTimeout(() => {+ const ta = textareaRef.current;+ if (ta) {+ ta.style.height = 'auto';+ ta.style.height = `${Math.min(ta.scrollHeight, 160)}px`;+ }+ if (live.current.phone && live.current.touch) micRef.current?.focus({ preventScroll: true });+ else if (ta) {+ ta.focus();+ ta.setSelectionRange(at, at);+ }+ }, 0);+ };++ const noteTyping = useCallback(() => {+ setLine((l) => (l?.kind === 'added' ? null : l));+ }, []);++ const closePopover = (toMic = true) => {+ setPopOpen(false);+ if (toMic) micRef.current?.focus({ preventScroll: true });+ };++ const hideMic = () => {+ if (spaceId) setMicHidden(spaceId, true);+ setPopOpen(false);+ say('Mic hidden. It comes back when dictation is set up.');+ setTimeout(() => textareaRef.current?.focus({ preventScroll: true }), 0);+ };++ // Esc anywhere stops and transcribes, before the composer's own Esc, unless a dialog or picker is open.+ useEffect(() => {+ if (phase !== 'recording') return;+ const onKey = (e: KeyboardEvent) => {+ if (e.key !== 'Escape' || e.defaultPrevented) return;+ if (document.querySelector('[aria-modal="true"], #kw-mention-list, [data-slash-popover]')) return;+ e.preventDefault();+ e.stopPropagation();+ stopRec(true);+ };+ document.addEventListener('keydown', onKey, true);+ return () => document.removeEventListener('keydown', onKey, true);+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [phase]);++ // The tab hidden for 30 s while dictating: stop and throw it away.+ useEffect(() => {+ if (phase === 'idle') return;+ let t: ReturnType<typeof setTimeout> | null = null;+ const onVis = () => {+ if (document.visibilityState === 'hidden') {+ t = setTimeout(() => {+ if (discard() !== 'idle') live.current.onToast?.('Dictation stopped: you left the chat.');+ }, HIDDEN_MS);+ } else if (t) {+ clearTimeout(t);+ t = null;+ }+ };+ document.addEventListener('visibilitychange', onVis);+ return () => {+ document.removeEventListener('visibilitychange', onVis);+ if (t) clearTimeout(t);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [phase === 'idle']);++ // Leaving the chat or the space (or the box going away): stop and discard, and say so.+ useEffect(+ () => () => {+ setPopOpen(false);+ clearAdded();+ if (discard() !== 'idle') live.current.onToast?.('Dictation stopped: you left the chat.');+ },+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [spaceId, chatKey],+ );++ // The popover: focus its first button; Esc or a click outside closes it.+ useEffect(() => {+ if (!popOpen) return;+ const t = setTimeout(() => popRef.current?.querySelector<HTMLButtonElement>('button')?.focus({ preventScroll: true }), 0);+ const onKey = (e: KeyboardEvent) => {+ if (e.key !== 'Escape') return;+ e.preventDefault();+ e.stopPropagation();+ closePopover(true);+ };+ const onDown = (e: Event) => {+ const n = e.target as Node | null;+ if (n && (popRef.current?.contains(n) || micRef.current?.contains(n))) return;+ closePopover(false);+ };+ document.addEventListener('keydown', onKey, true);+ document.addEventListener('pointerdown', onDown, true);+ return () => {+ clearTimeout(t);+ document.removeEventListener('keydown', onKey, true);+ document.removeEventListener('pointerdown', onDown, true);+ };+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [popOpen]);++ // The popover only belongs to the muted mic.+ useEffect(() => {+ if (view !== 'muted' && popOpen) setPopOpen(false);+ }, [view, popOpen]);++ return {+ view,+ phase,+ busy: phase === 'recording' || phase === 'transcribing' || phase === 'asking',+ line,+ canUndo,+ silent,+ startedAt,+ levelRef,+ secure,+ why,+ popOpen: popOpen && view === 'muted',+ announce,+ micRef,+ popRef,+ toggle,+ cancel,+ retry,+ dismiss,+ undo,+ closePopover,+ hideMic,+ noteTyping,+ noteSent: noteTyping,+ };+}++// ---------------------------------------------------------------------------------------------------+// The mic button++export function MicButton({ d, phone }: { d: Dictation; phone: boolean }) {+ if (d.view === 'hidden') return null;+ const state = d.view === 'muted' ? 'muted' : d.phase === 'recording' ? 'rec' : d.phase === 'transcribing' ? 'busy' : 'ready';+ const size = phone ? 'w-11 h-11 ml-1.5 focus-visible:outline-[#b8adff]' : 'w-11 h-11 sm:w-9 sm:h-9 focus-visible:outline-sky-400';+ const look =+ state === 'rec'+ ? 'bg-violet-500/[0.22] shadow-[inset_0_0_0_1px_rgb(167_139_250/0.55)] text-violet-200'+ : state === 'busy'+ ? 'text-violet-300 cursor-default'+ : state === 'muted'+ ? d.popOpen+ ? 'bg-white/[0.06] text-zinc-300'+ : phone+ ? 'text-[#6e6896] hover:bg-white/[0.06]'+ : 'text-zinc-500 hover:text-zinc-300 hover:bg-white/[0.08]'+ : phone+ ? 'text-[#a39dcc] hover:text-zinc-100 hover:bg-white/[0.06] active:bg-white/[0.06]'+ : 'text-zinc-300 hover:text-zinc-50 hover:bg-white/[0.08]';+ const icon = phone ? 18 : 17;+ return (+ <button+ ref={d.micRef}+ type="button"+ data-mic={state}+ onClick={d.toggle}+ aria-label={state === 'muted' ? 'Dictate (not set up)' : 'Dictate'}+ aria-pressed={state === 'muted' ? undefined : state === 'rec'}+ aria-haspopup={state === 'muted' ? 'dialog' : undefined}+ aria-expanded={state === 'muted' ? d.popOpen : undefined}+ aria-disabled={state === 'busy' || d.phase === 'asking' ? true : undefined}+ title={+ phone+ ? undefined+ : state === 'rec'+ ? 'Stop and turn it into text (Esc)'+ : state === 'busy'+ ? 'Turning speech into text…'+ : state === 'muted'+ ? 'Dictation isn’t set up in this space'+ : 'Dictate: speak, then edit before you send'+ }+ className={`${size} ${look} rounded-xl flex items-center justify-center flex-shrink-0 transition-colors focus-visible:outline focus-visible:outline-2`}+ >+ {state === 'rec' ? (+ <Square size={phone ? 13 : 12} fill="#ddd6fe" color="#ddd6fe" aria-hidden="true" />+ ) : state === 'busy' ? (+ <Loader2 size={icon} className="kw-dict-spin" aria-hidden="true" />+ ) : (+ <Mic size={icon} aria-hidden="true" />+ )}+ </button>+ );+}++// ---------------------------------------------------------------------------------------------------+// The dictation line: the form's first row while anything is happening++function LineButton({ phone, onClick, children, label }: { phone: boolean; onClick: () => void; children: React.ReactNode; label?: string }) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-label={label}+ className={`inline-flex items-center gap-1.5 flex-none rounded-[10px] border border-hairline-strong bg-white/[0.03] text-zinc-200 font-medium hover:bg-white/[0.08] hover:text-zinc-50 focus-visible:outline focus-visible:outline-2 ${+ phone ? 'min-h-11 px-3 text-[13px] focus-visible:outline-[#b8adff]' : 'min-h-7 px-2.5 text-[12px] focus-visible:outline-sky-400'+ }`}+ >+ {children}+ </button>+ );+}++function CloseButton({ phone, onClick }: { phone: boolean; onClick: () => void }) {+ return (+ <button+ type="button"+ onClick={onClick}+ aria-label="Dismiss"+ className={`${phone ? 'w-11 h-11 focus-visible:outline-[#b8adff]' : 'w-7 h-7 focus-visible:outline-sky-400'} flex-none rounded-lg grid place-items-center text-zinc-400 hover:text-zinc-200 hover:bg-white/[0.06] focus-visible:outline focus-visible:outline-2`}+ >+ <X size={14} aria-hidden="true" />+ </button>+ );+}++function Elapsed({ startedAt }: { startedAt: number }) {+ const [, tick] = useReducer((x: number) => x + 1, 0);+ useEffect(() => {+ const t = setInterval(tick, 250);+ return () => clearInterval(t);+ }, []);+ const s = (Date.now() - startedAt) / 1000;+ if (s >= WARN_SECONDS)+ return (+ <span data-dictation-time className="tabular-nums text-[#fcd34d] flex-none" aria-hidden="true">+ {clock(MAX_SECONDS - s)} left+ </span>+ );+ return (+ <span data-dictation-time className="tabular-nums text-zinc-400 flex-none" aria-hidden="true">+ {clock(s)}+ </span>+ );+}++function Level({ levelRef }: { levelRef: RefObject<number> }) {+ const bars = useRef<(HTMLElement | null)[]>([]);+ useEffect(() => {+ let raf = 0;+ let last = 0;+ const loop = (t: number) => {+ if (t - last >= 66) {+ last = t;+ const s = barScales(levelRef.current ?? 0);+ bars.current.forEach((b, i) => {+ if (b) b.style.transform = `scaleY(${s[i]})`;+ });+ }+ raf = requestAnimationFrame(loop);+ };+ raf = requestAnimationFrame(loop);+ return () => cancelAnimationFrame(raf);+ }, [levelRef]);+ return (+ <span data-dictation-level className="flex items-center gap-0.5 h-4 flex-none" aria-hidden="true">+ {[0, 1, 2, 3, 4].map((i) => (+ <i+ key={i}+ ref={(el) => {+ bars.current[i] = el;+ }}+ className="block w-[3px] h-4 rounded-sm bg-[#c4b5fd] origin-center"+ style={{ transform: 'scaleY(0.2)' }}+ />+ ))}+ </span>+ );+}++export function DictationLine({ d, phone, botName, reduced }: { d: Dictation; phone: boolean; botName: string; reduced: boolean }) {+ const l = d.line;+ if (!l) return null;+ const multi = l.kind === 'bad' || l.kind === 'warn';+ const box = `basis-full min-w-0 flex ${multi ? 'items-start pt-1' : 'items-center'} gap-2 ${+ phone ? 'min-h-11 text-[13px] pl-1.5' : 'min-h-8 text-[12.5px] pl-2'+ } pr-1 leading-[18px] text-zinc-300 border-b border-hairline pb-1.5 mb-0.5`;+ const lead = `flex ${multi ? 'items-start' : 'items-center'} gap-2 min-w-0 flex-1`;+ if (l.kind === 'asking')+ return (+ <div data-dictation-line="asking" className={box}>+ <span className="min-w-0">Allow the microphone in your browser’s prompt.</span>+ </div>+ );+ if (l.kind === 'recording')+ return (+ <div data-dictation-line="recording" className={box}>+ <span className={lead}>+ <span className="w-2 h-2 rounded-full bg-[#fb7185] shadow-[0_0_0_3px_rgb(251_113_133/0.18)] flex-none" aria-hidden="true" />+ <b className="font-semibold text-zinc-100 flex-none">Listening</b>+ <Elapsed startedAt={d.startedAt} />+ {!reduced && <Level levelRef={d.levelRef} />}+ {d.silent ? (+ <span data-dictation-silent className="text-[#fcd34d] truncate min-w-0">+ Can’t hear anything. Check the microphone.+ </span>+ ) : (+ !phone && <span className="text-zinc-400 truncate min-w-0">· Esc or the mic stops · nothing goes to {botName} until you press Send</span>+ )}+ </span>+ <LineButton phone={phone} onClick={d.cancel}>+ Cancel+ </LineButton>+ </div>+ );+ if (l.kind === 'transcribing')+ return (+ <div data-dictation-line="transcribing" className={box}>+ <span className={lead}>+ <Loader2 size={14} className="kw-dict-spin text-[#c4b5fd] flex-none" aria-hidden="true" />+ <b className="font-semibold text-zinc-100 min-w-0">Turning speech into text…</b>+ <span className="tabular-nums text-zinc-400 flex-none whitespace-nowrap">{clock(l.seconds)} recorded</span>+ </span>+ <LineButton phone={phone} onClick={d.cancel}>+ Cancel+ </LineButton>+ </div>+ );+ if (l.kind === 'added')+ return (+ <div data-dictation-line="added" className={box}>+ <span className={lead}>+ <Check size={14} className="text-[#5eead4] flex-none" aria-hidden="true" />+ <span className="text-zinc-200 min-w-0">Added {wordsLabel(l.words)}. Read them over, then press Send.</span>+ </span>+ {d.canUndo && (+ <LineButton phone={phone} onClick={d.undo}>+ <Undo2 size={13} aria-hidden="true" />+ Undo+ </LineButton>+ )}+ </div>+ );+ if (l.kind === 'bad')+ return (+ <div data-dictation-line="bad" role="alert" className={box}>+ <span className={lead}>+ <AlertCircle size={14} className={`text-bad flex-none ${phone ? 'mt-0.5' : 'mt-[7px]'}`} aria-hidden="true" />+ <span className={`text-bad min-w-0 break-words ${phone ? '' : 'pt-[5px]'}`}>{l.text}</span>+ </span>+ {l.retry && (+ <LineButton phone={phone} onClick={d.retry}>+ <RotateCcw size={13} aria-hidden="true" />+ Try again+ </LineButton>+ )}+ <CloseButton phone={phone} onClick={d.dismiss} />+ </div>+ );+ return (+ <div data-dictation-line="warn" role="alert" className={box}>+ <span className={lead}>+ <MicOff size={14} className={`text-[#fcd34d] flex-none ${phone ? 'mt-0.5' : 'mt-[7px]'}`} aria-hidden="true" />+ <span className={`text-[#fde68a] min-w-0 break-words ${phone ? '' : 'pt-[5px]'}`}>{l.text}</span>+ </span>+ <CloseButton phone={phone} onClick={d.dismiss} />+ </div>+ );+}++/** The polite live region: one sentence per change. Always mounted, so it can be read. */+export function DictationAnnouncer({ d }: { d: Dictation }) {+ return (+ <span role="status" aria-live="polite" className="sr-only" data-dictation-announce>+ {d.announce.text ? <span key={d.announce.n}>{d.announce.text}</span> : null}+ </span>+ );+}++// ---------------------------------------------------------------------------------------------------+// "Dictation isn't set up in this space"++export function DictationSetupPopover({ d, phone, onOpenAccounts }: { d: Dictation; phone: boolean; onOpenAccounts?: () => void }) {+ if (!d.popOpen) return null;+ const accounts = d.secure && onOpenAccounts;+ const btn = phone ? 'min-h-11 px-3.5 text-[13px]' : 'min-h-8 px-3 text-[12.5px]';+ return (+ <div+ ref={d.popRef}+ role="dialog"+ aria-labelledby="kw-dict-pop-title"+ data-dictation-popover+ className={`kw-dict-pop absolute bottom-full mb-2 z-50 ${phone ? 'left-0 right-0' : 'right-[44px] w-[340px] max-w-[calc(100%-16px)]'} bg-surface-overlay border border-hairline-strong rounded-xl shadow-xl p-3.5`}+ >+ <h4 id="kw-dict-pop-title" className="m-0 mb-1.5 flex items-center gap-2 text-[14px] font-semibold text-zinc-50">+ <Mic size={15} aria-hidden="true" />+ Dictation isn’t set up in this space+ </h4>+ <p className="m-0 mb-3 text-[13px] leading-[19px] text-zinc-300">{d.why}</p>+ <div className="flex flex-wrap gap-2">+ {accounts && (+ <button+ type="button"+ onClick={() => {+ d.closePopover(false);+ onOpenAccounts?.();+ }}+ className={`${btn} inline-flex items-center rounded-[10px] bg-accent-gradient text-white font-semibold hover:brightness-110 focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-sky-300`}+ >+ Open Apps & accounts+ </button>+ )}+ <button+ type="button"+ onClick={d.hideMic}+ className={`${btn} inline-flex items-center rounded-[10px] border border-hairline-strong bg-white/[0.03] text-zinc-200 font-medium hover:bg-white/[0.08] focus-visible:outline focus-visible:outline-2 focus-visible:outline-sky-400`}+ >+ Hide the mic+ </button>+ </div>+ <p className="m-0 mt-3 pt-2.5 border-t border-hairline text-[12px] leading-[17px] text-zinc-400">+ OpenAI turns what you say into text with this space’s key. The words land in this box and nothing goes to a bot until you press Send.+ </p>+ </div>+ );+}diff --git a/frontend/src/dictation.ts b/frontend/src/dictation.tsnew file mode 100644index 00000000..0d24ab85--- /dev/null+++ b/frontend/src/dictation.ts@@ -0,0 +1,276 @@+// Dictation: the mic in the message box (Mira, autonomy/dictation/design.md; Juno's #610 routes).+// The server turns a recording into text with the space's OpenAI key; nothing goes to a bot before Send.++/** `GET /api/spaces/:id/transcribe`. */+export interface Availability {+ available: boolean;+ source: string | null;+ why: string | null;+}++/** The answer to a recording: the words, or the server's refusal as it sent it. */+export type TranscribeResult =+ | { ok: true; text: string }+ | { ok: false; status: number; code: string | null; error: string; why?: string | null };++/** A network failure (status 0): nothing came back from kwant. */+export const NETWORK_ERROR = 'Couldn’t reach the server to turn this into text.';+export const NO_WORDS = 'Didn’t catch any words. Try again a little closer to the microphone.';+export const INSECURE_WHY = 'Your browser only lets pages on https, or on this computer, use the microphone. Open kwant bots that way to dictate.';+/** The longest recording, in seconds (about 2.4 MB of opus, far under the server's 25 MB). */+export const MAX_SECONDS = 600;+/** From here the timer says how much is left, in amber. */+export const WARN_SECONDS = 570;+/** No sound for this long: "Can't hear anything." */+export const SILENCE_MS = 4000;+export const SILENCE_LEVEL = 0.02;+/** The "Added n words" line goes away after this. */+export const ADDED_MS = 8000;+/** The tab hidden this long while dictating stops and discards it. */+export const HIDDEN_MS = 30000;++// ---------------------------------------------------------------------------------------------------+// Availability, cached per space++type Cached = Availability | 'error';+const cache = new Map<string, Cached>();+const inflight = new Map<string, Promise<Cached>>();+const listeners = new Set<() => void>();++const hiddenKey = (spaceId: string) => `kwnt:dictation-hidden:${spaceId}`;++export function micHidden(spaceId: string): boolean {+ try {+ return localStorage.getItem(hiddenKey(spaceId)) === '1';+ } catch {+ return false;+ }+}++export function setMicHidden(spaceId: string, hidden: boolean): void {+ try {+ if (hidden) localStorage.setItem(hiddenKey(spaceId), '1');+ else localStorage.removeItem(hiddenKey(spaceId));+ } catch {+ /* private mode: the mic just stays */+ }+ emit();+}++function emit() {+ for (const l of [...listeners]) l();+}++/** Called when the cache or the hidden flag changes. */+export function onDictationChange(l: () => void): () => void {+ listeners.add(l);+ return () => {+ listeners.delete(l);+ };+}++/** What's known for a space now: an answer, 'error' (fetch failed or 404), or undefined (not asked yet). */+export function cachedAvailability(spaceId: string): Cached | undefined {+ return cache.get(spaceId);+}++/** Sets a space's availability (a 409 `no_transcriber` from the POST flips it to not set up). */+export function setAvailability(spaceId: string, a: Availability): void {+ cache.set(spaceId, a);+ if (a.available && globalThis.isSecureContext !== false && micHidden(spaceId)) setMicHidden(spaceId, false);+ emit();+}++export function parseAvailability(raw: unknown): Availability | null {+ if (!raw || typeof raw !== 'object') return null;+ const r = raw as Record<string, unknown>;+ if (typeof r.available !== 'boolean') return null;+ return {+ available: r.available,+ source: typeof r.source === 'string' ? r.source : null,+ why: typeof r.why === 'string' && r.why.trim() ? r.why : null,+ };+}++/** Reads `GET /api/spaces/:id/transcribe`, once per space unless `fresh`. */+export function getAvailability(spaceId: string, opts: { fresh?: boolean } = {}): Promise<Cached> {+ const have = cache.get(spaceId);+ if (have !== undefined && !opts.fresh) return Promise.resolve(have);+ const going = inflight.get(spaceId);+ if (going) return going;+ const p = fetch(`/api/spaces/${encodeURIComponent(spaceId)}/transcribe`, { credentials: 'same-origin' })+ .then(async (res) => (res.ok ? parseAvailability(await res.json().catch(() => null)) ?? 'error' : 'error'))+ .catch((): Cached => 'error')+ .then((a) => {+ inflight.delete(spaceId);+ cache.set(spaceId, a);+ // A key was added: "Hide the mic" was about not having one, so the mic comes back.+ if (a !== 'error' && a.available && micHidden(spaceId) && globalThis.isSecureContext !== false) setMicHidden(spaceId, false);+ emit();+ return a;+ });+ inflight.set(spaceId, p);+ return p;+}++/** Forget every answer and ask again (Space settings closed, or the window got focus back). */+export function refreshDictation(): void {+ const spaces = [...cache.keys()];+ cache.clear();+ for (const s of spaces) void getAvailability(s);+ emit();+}++/** `POST /api/spaces/:id/transcribe?lang=xx` with the recording as the body. Throws only on abort. */+export async function transcribe(spaceId: string, blob: Blob, lang: string | null, signal?: AbortSignal): Promise<TranscribeResult> {+ const q = lang ? `?lang=${encodeURIComponent(lang)}` : '';+ let res: Response;+ try {+ res = await fetch(`/api/spaces/${encodeURIComponent(spaceId)}/transcribe${q}`, {+ method: 'POST',+ body: blob,+ headers: { 'Content-Type': blob.type || 'audio/webm' },+ credentials: 'same-origin',+ signal,+ });+ } catch (err) {+ if (signal?.aborted || (err as { name?: string })?.name === 'AbortError') throw err;+ return { ok: false, status: 0, code: 'network', error: NETWORK_ERROR };+ }+ let body: Record<string, unknown> | null = null;+ try {+ body = (await res.json()) as Record<string, unknown>;+ } catch {+ if (signal?.aborted) throw new DOMException('Aborted', 'AbortError');+ }+ if (res.ok && body && typeof body.text === 'string') return { ok: true, text: body.text };+ const error = body && typeof body.error === 'string' && body.error.trim() ? body.error : res.ok ? 'The answer couldn’t be read.' : `Dictation failed (${res.status}).`;+ return {+ ok: false,+ status: res.ok ? 502 : res.status,+ code: body && typeof body.code === 'string' ? body.code : null,+ error,+ why: body && typeof body.why === 'string' ? body.why : null,+ };+}++// ---------------------------------------------------------------------------------------------------+// Pure helpers++export type MicView = 'ready' | 'muted' | 'hidden';++/**+ * Whether the mic shows, and how (design §2). `supported`: the browser has MediaRecorder (and+ * getUserMedia where it's allowed); `secure`: window.isSecureContext; `availability`: the GET's answer,+ * 'error' when it failed or 404'd, undefined while it's asked; `hidden`: "Hide the mic" in this space.+ */+export function micVisible(s: { supported: boolean; secure: boolean; availability: Cached | undefined; hidden: boolean }): MicView {+ if (!s.supported) return 'hidden';+ if (s.availability === undefined || s.availability === 'error') return 'hidden';+ if (s.secure && s.availability.available) return 'ready';+ if (s.hidden) return 'hidden';+ return 'muted';+}++/** Whether this browser can record at all. Over plain http getUserMedia is missing; that's `secure`'s job. */+export function browserSupports(w: { MediaRecorder?: unknown; isSecureContext?: boolean; navigator?: { mediaDevices?: { getUserMedia?: unknown } } }): boolean {+ if (typeof w.MediaRecorder !== 'function') return false;+ if (w.isSecureContext === false) return true;+ return typeof w.navigator?.mediaDevices?.getUserMedia === 'function';+}++export interface Inserted {+ value: string;+ /** Where the inserted piece (with any added spaces) starts and ends in `value`. */+ from: number;+ to: number;+ piece: string;+ /** The caret: right after the words. */+ caret: number;+}++/**+ * Puts dictated words into the box at `at` (clamped to the text): a space before unless it's the start+ * or there's whitespace there, a space after unless it's the end or the next character is whitespace or+ * punctuation. Nothing typed is replaced.+ */+export function insertDictated(value: string, at: number, text: string): Inserted {+ const words = text.trim();+ const pos = Math.max(0, Math.min(Number.isFinite(at) ? at : value.length, value.length));+ const before = value.slice(0, pos);+ const after = value.slice(pos);+ const lead = pos > 0 && !/\s$/.test(before) ? ' ' : '';+ const trail = after.length > 0 && !/^[\s.,;:!?…)\]}"'’”»]/.test(after) ? ' ' : '';+ const piece = `${lead}${words}${trail}`;+ return { value: before + piece + after, from: pos, to: pos + piece.length, piece, caret: pos + lead.length + words.length };+}++/** Takes the words back out, only if they are still there unchanged; null otherwise. */+export function undoDictated(value: string, ins: Pick<Inserted, 'from' | 'to' | 'piece'>): string | null {+ if (value.slice(ins.from, ins.to) !== ins.piece) return null;+ return value.slice(0, ins.from) + value.slice(ins.to);+}++export function wordCount(text: string): number {+ const t = text.trim();+ return t ? t.split(/\s+/).length : 0;+}++export function wordsLabel(n: number): string {+ return n === 1 ? '1 word' : `${n.toLocaleString('en-US')} words`;+}++/** The browser's language as a two-letter hint, or null. */+export function langHint(navigatorLanguage: string | null | undefined): string | null {+ const l = (navigatorLanguage ?? '').slice(0, 2).toLowerCase();+ return /^[a-z]{2}$/.test(l) ? l : null;+}++/** What to say when the browser refuses the microphone (design §7), by the error's `name`. */+export function micErrorText(name: string | null | undefined, phone: boolean): string {+ switch (name) {+ case 'NotAllowedError':+ case 'SecurityError':+ return phone+ ? 'The microphone is blocked for this site. Allow it in your browser’s site settings, then press the mic again.'+ : 'The microphone is blocked for this site. Allow it from the icon at the left of the address bar, then press the mic again.';+ case 'NotFoundError':+ case 'OverconstrainedError':+ return phone+ ? 'No microphone found. Check your phone’s microphone settings for this browser, then press the mic again.'+ : 'No microphone found. Plug one in or pick one in your system’s sound settings, then press the mic again.';+ case 'NotReadableError':+ case 'AbortError':+ return 'The microphone is in use by another app. Close it there, then press the mic again.';+ default:+ return 'Couldn’t start the microphone. Try again, or reload the page.';+ }+}++/** Try again (same recording) only where saying it again wouldn't help: busy, OpenAI failed, no network. */+export function canRetry(status: number, code: string | null | undefined): boolean {+ if (status === 0 || code === 'network') return true;+ if (status === 429 && code === 'busy') return true;+ if (status === 502) return true;+ return false;+}++/** m:ss */+export function clock(seconds: number): string {+ const s = Math.max(0, Math.floor(seconds));+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;+}++/** The level bars: the centre is the level, its neighbours 0.7x and 0.35x, never under 0.2. */+export function barScales(level: number): number[] {+ const l = Math.max(0, Math.min(1, level));+ return [0.35, 0.7, 1, 0.7, 0.35].map((k) => Math.max(0.2, Math.min(1, l * k)));+}++/** RMS of a time-domain buffer (-1..1), scaled so normal speech reaches about 1. */+export function rmsLevel(buf: ArrayLike<number>): number {+ if (!buf.length) return 0;+ let sum = 0;+ for (let i = 0; i < buf.length; i++) sum += buf[i] * buf[i];+ return Math.min(1, Math.sqrt(sum / buf.length) * 4);+}diff --git a/frontend/src/styles/modern.css b/frontend/src/styles/modern.cssindex 7d1ec5f1..054ca6a3 100644--- a/frontend/src/styles/modern.css+++ b/frontend/src/styles/modern.css@@ -975,6 +975,10 @@ button.dv-sha { cursor: copy; } button.dv-sha:hover { color: var(--accent); bord.dv-cmd pre { margin: 0; padding: 9px 10px; font: 500 12px/19px 'JetBrains Mono', monospace; color: var(--t1); white-space: pre-wrap; word-break: break-all; }.dv-cmd pre .ps { color: var(--accent); user-select: none; }+@media (prefers-reduced-motion: reduce) {+ .kw-dict-spin, .kw-dict-pop { animation: none !important; }+}+@media (prefers-reduced-motion: reduce) {.dv-led::after, .dv-led[data-ping]::after, .dv-node::before, .dv-caret, .dv-stamp { animation: none !important; }.dv-led[data-s="run"]::after { opacity: .5; transform: scale(1.6); }@@ -1021,6 +1025,12 @@ button.dv-sha { cursor: copy; } button.dv-sha:hover { color: var(--accent); bord.kw-pin-enter { animation: kw-pin-enter 160ms ease-out; }}+/* Dictation (design.md §4, §6): the spinner turns in 0.9 s, the popover rises 4 px in 140 ms; both still under reduced motion. */+.kw-dict-spin { animation: kw-dict-spin 0.9s linear infinite; }+@keyframes kw-dict-spin { to { transform: rotate(360deg); } }+.kw-dict-pop { animation: kw-dict-pop 140ms ease-out both; }+@keyframes kw-dict-pop { from { opacity: 0; transform: translateY(4px); } to { opacity: 1; transform: none; } }+/* Fix it "Send to…" (#609, design §8): the picker's popover and phone sheet. Static under reduced motion. */@keyframes kw-st-pop { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }@keyframes kw-st-sheet { from { transform: translateY(100%); } to { transform: none; } }diff --git a/frontend/tests/dictation.test.mjs b/frontend/tests/dictation.test.mjsnew file mode 100644index 00000000..495cea5d--- /dev/null+++ b/frontend/tests/dictation.test.mjs@@ -0,0 +1,612 @@+// Dictation mic (Mira, autonomy/dictation/design.md; Juno's #610 routes). The pure helpers, then the mic,+// the dictation line and the "isn't set up" popover inside the real ChatView, against a fake+// /transcribe, a fake microphone and a fake MediaRecorder. Made-up words only; no network.+import assert from 'node:assert/strict';+import test from 'node:test';+import { readFileSync } from 'node:fs';+import { JSDOM } from 'jsdom';+import { loadBundled } from './bundle.mjs';++const dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/', pretendToBeVisual: true });+for (const k of ['window', 'document', 'navigator', 'HTMLElement', 'HTMLButtonElement', 'HTMLTextAreaElement', 'Element', 'Node', 'Event', 'KeyboardEvent', 'MouseEvent', 'FocusEvent', 'MutationObserver', 'requestAnimationFrame', 'cancelAnimationFrame', 'getComputedStyle', 'CSS']) {+ if (!(k in dom.window)) continue;+ Object.defineProperty(globalThis, k, { value: dom.window[k], configurable: true, writable: true });+}+const store = new Map();+const ls = { getItem: (k) => (store.has(k) ? store.get(k) : null), setItem: (k, v) => void store.set(k, String(v)), removeItem: (k) => void store.delete(k) };+Object.defineProperty(globalThis, 'localStorage', { value: ls, configurable: true, writable: true });+Object.defineProperty(dom.window, 'localStorage', { value: ls, configurable: true });+const media = { phone: false, coarse: false };+dom.window.matchMedia = (q) => ({+ matches: q.includes('pointer: coarse') ? media.coarse : q.includes('max-width: 767px') || q.includes('max-width: 639px') ? media.phone : false,+ media: q,+ addEventListener() {},+ removeEventListener() {},+ addListener() {},+ removeListener() {},+});+globalThis.matchMedia = dom.window.matchMedia;+globalThis.ResizeObserver ??= class { observe() {} unobserve() {} disconnect() {} };+dom.window.ResizeObserver ??= globalThis.ResizeObserver;+globalThis.IntersectionObserver ??= class { observe() {} unobserve() {} disconnect() {} };+dom.window.HTMLElement.prototype.scrollIntoView ??= function () {};+dom.window.HTMLElement.prototype.scrollTo ??= function () {};+globalThis.IS_REACT_ACT_ENVIRONMENT = false;++// The fake microphone and recorder.+const mic = { refuse: null, streams: 0, stopped: 0 };+class FakeRecorder {+ constructor(stream) {+ this.stream = stream;+ this.state = 'inactive';+ this.mimeType = 'audio/webm;codecs=opus';+ }+ start() {+ this.state = 'recording';+ }+ stop() {+ this.state = 'inactive';+ this.ondataavailable?.({ data: new Blob(['made-up audio'], { type: this.mimeType }) });+ this.onstop?.();+ }+}+dom.window.MediaRecorder = FakeRecorder;+globalThis.MediaRecorder = FakeRecorder;+Object.defineProperty(dom.window, 'isSecureContext', { value: true, configurable: true, writable: true });+Object.defineProperty(dom.window.navigator, 'mediaDevices', {+ configurable: true,+ value: {+ getUserMedia: async () => {+ if (mic.refuse) throw Object.assign(new Error('no'), { name: mic.refuse });+ mic.streams++;+ const track = { stop: () => mic.stopped++, addEventListener() {} };+ return { getTracks: () => [track], getAudioTracks: () => [track] };+ },+ },+});++// The fake server: GET answers per space, POST answers from a queue (or waits for `release`).+const server = { get: {}, posts: [], answers: [], hold: null };+globalThis.fetch = async (url, init = {}) => {+ const u = String(url);+ const m1 = u.match(/^\/api\/spaces\/([^/]+)\/transcribe(\?.*)?$/);+ if (!m1) return { ok: true, status: 200, json: async () => [] };+ const space = decodeURIComponent(m1[1]);+ if ((init.method ?? 'GET') === 'GET') {+ const a = server.get[space];+ if (a === 'down') throw new TypeError('fetch failed');+ if (!a) return { ok: false, status: 404, json: async () => ({ error: 'no such space', code: 'no_space' }) };+ return { ok: true, status: 200, json: async () => a };+ }+ server.posts.push({ space, url: u, type: init.headers?.['Content-Type'], body: init.body });+ if (server.hold) await server.hold;+ const [status, body] = server.answers.shift() ?? [200, { text: 'made-up words', source: 'openai' }];+ if (status === 0) throw new TypeError('fetch failed');+ return { ok: status >= 200 && status < 300, status, json: async () => body };+};++const ui = await loadBundled(`+ import React from 'react';+ import { flushSync } from 'react-dom';+ import { createRoot } from 'react-dom/client';+ import { ChatView } from './src/components/ChatView';+ export * from './src/dictation';+ export const mount = (p) => {+ const host = document.createElement('div');+ document.body.appendChild(host);+ const root = createRoot(host);+ const render = (q) => flushSync(() => root.render(React.createElement(ChatView, q)));+ render(p);+ return { host, render, unmount: () => { root.unmount(); host.remove(); } };+ };+ export const act = (fn) => flushSync(fn);+`);++const settle = async (n = 15) => {+ for (let i = 0; i < n; i++) await new Promise((r) => setTimeout(r, 0));+};+const props = (extra = {}) => ({+ title: 'Wren',+ subtitle: 'Newsletters and social posts',+ messages: [],+ streamingText: '',+ streamingThinking: '',+ isStreaming: false,+ pendingApprovals: [],+ onSendMessage: () => {},+ onResolveApproval: () => {},+ onCancelDiscussion: () => {},+ kwants: [],+ teams: [],+ contextKey: 'k:wren',+ ...extra,+});+const $ = (h, s) => h.querySelector(s);+const micBtn = (h) => $(h, '[data-mic]');+const sendBtn = (h) => $(h, 'form[data-composer-form] button[type="submit"]');+const line = (h) => $(h, '[data-dictation-line]');+const click = (el) => ui.act(() => el.dispatchEvent(new window.MouseEvent('click', { bubbles: true })));+const typeInto = (ta, value) =>+ ui.act(() => {+ Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value').set.call(ta, value);+ ta.dispatchEvent(new window.Event('input', { bubbles: true }));+ });+const reset = () => {+ media.phone = false;+ media.coarse = false;+ mic.refuse = null;+ server.answers = [];+ server.posts = [];+ server.hold = null;+};++// ---------------------------------------------------------------------------------------------------+// 1. insertDictated: spacing++test('insertDictated: start, middle, end, before punctuation, and a caret past the end is clamped', () => {+ // empty box+ assert.deepEqual(ui.insertDictated('', 0, ' Book a table. '), { value: 'Book a table.', from: 0, to: 13, piece: 'Book a table.', caret: 13 });+ // start of typed text: a space after, none before+ let r = ui.insertDictated('for four', 0, 'Book a table');+ assert.equal(r.value, 'Book a table for four');+ assert.equal(r.piece, 'Book a table ');+ assert.equal(r.caret, 12);+ // middle, between two words with no space at the caret+ r = ui.insertDictated('Wren,plan', 5, 'please');+ assert.equal(r.value, 'Wren, please plan');+ // after a space: no extra space before+ r = ui.insertDictated('Wren, ', 6, 'plan it');+ assert.equal(r.value, 'Wren, plan it');+ assert.equal(r.piece, 'plan it');+ // end of text with no trailing space+ r = ui.insertDictated('Wren, plan the spring newsletter.', 33, 'Use three quotes.');+ assert.equal(r.value, 'Wren, plan the spring newsletter. Use three quotes.');+ assert.equal(r.caret, r.value.length);+ // before punctuation: no space after+ r = ui.insertDictated('Call Ana.', 8, 'tomorrow');+ assert.equal(r.value, 'Call Ana tomorrow.');+ r = ui.insertDictated('Call Ana, then', 8, 'and Ben');+ assert.equal(r.value, 'Call Ana and Ben, then');+ // typed while recording: the saved caret is past the (shorter) text now+ r = ui.insertDictated('Hi', 40, 'there');+ assert.equal(r.value, 'Hi there');+ assert.equal(r.from, 2);+ r = ui.insertDictated('Hi', -3, 'there');+ assert.equal(r.value, 'there Hi');+});++// ---------------------------------------------------------------------------------------------------+// 2. Undo only when unchanged++test('undoDictated: takes back exactly the inserted piece, only while it is unchanged', () => {+ const r = ui.insertDictated('Wren, plan it.', 10, 'the spring newsletter');+ assert.equal(r.value, 'Wren, plan the spring newsletter it.');+ assert.equal(ui.undoDictated(r.value, r), 'Wren, plan it.');+ assert.equal(ui.undoDictated(r.value.replace('spring', 'autumn'), r), null, 'edited words stay');+ assert.equal(ui.undoDictated(`X${r.value}`, r), null, 'moved words stay');+ assert.equal(ui.undoDictated('', r), null);+});++// ---------------------------------------------------------------------------------------------------+// 3. micVisible: every row of §2++test('micVisible: ready, muted, hidden for every row of the availability table', () => {+ const yes = { available: true, source: 'openai', why: null };+ const no = { available: false, source: null, why: 'Add an OpenAI API key in Apps & accounts to dictate.' };+ const v = (o) => ui.micVisible({ supported: true, secure: true, availability: yes, hidden: false, ...o });+ assert.equal(v({}), 'ready');+ assert.equal(v({ availability: no }), 'muted');+ assert.equal(v({ availability: no, hidden: true }), 'hidden', 'Hide the mic');+ assert.equal(v({ hidden: true }), 'ready', 'a key brings the mic back even if it was hidden');+ assert.equal(v({ availability: 'error' }), 'hidden', 'GET failed or 404');+ assert.equal(v({ availability: undefined }), 'hidden', 'not asked yet');+ assert.equal(v({ supported: false }), 'hidden', 'no MediaRecorder');+ assert.equal(v({ secure: false }), 'muted', 'plain http: muted, popover explains');+ assert.equal(v({ secure: false, hidden: true }), 'hidden');+ // what "supported" means+ const gum = { mediaDevices: { getUserMedia() {} } };+ assert.equal(ui.browserSupports({ MediaRecorder: FakeRecorder, isSecureContext: true, navigator: gum }), true);+ assert.equal(ui.browserSupports({ isSecureContext: true, navigator: gum }), false);+ assert.equal(ui.browserSupports({ MediaRecorder: FakeRecorder, isSecureContext: true, navigator: {} }), false);+ assert.equal(ui.browserSupports({ MediaRecorder: FakeRecorder, isSecureContext: false, navigator: {} }), true, 'http hides getUserMedia; the mic shows muted');+ assert.equal(ui.langHint('en-GB'), 'en');+ assert.equal(ui.langHint('PT'), 'pt');+ assert.equal(ui.langHint('x'), null);+ assert.equal(ui.langHint(''), null);+ assert.equal(ui.wordCount(' one two\nthree '), 3);+ assert.equal(ui.wordsLabel(1), '1 word');+ assert.equal(ui.wordsLabel(23), '23 words');+ assert.equal(ui.clock(12), '0:12');+ assert.equal(ui.clock(600), '10:00');+});++// ---------------------------------------------------------------------------------------------------+// 4. Browser errors++test('micErrorText: each getUserMedia error, desktop and phone', () => {+ const blockedD = 'The microphone is blocked for this site. Allow it from the icon at the left of the address bar, then press the mic again.';+ const blockedP = 'The microphone is blocked for this site. Allow it in your browser’s site settings, then press the mic again.';+ for (const n of ['NotAllowedError', 'SecurityError']) {+ assert.equal(ui.micErrorText(n, false), blockedD);+ assert.equal(ui.micErrorText(n, true), blockedP);+ }+ for (const n of ['NotFoundError', 'OverconstrainedError']) {+ assert.equal(ui.micErrorText(n, false), 'No microphone found. Plug one in or pick one in your system’s sound settings, then press the mic again.');+ assert.equal(ui.micErrorText(n, true), 'No microphone found. Check your phone’s microphone settings for this browser, then press the mic again.');+ }+ for (const n of ['NotReadableError', 'AbortError'])+ for (const p of [false, true]) assert.equal(ui.micErrorText(n, p), 'The microphone is in use by another app. Close it there, then press the mic again.');+ assert.equal(ui.micErrorText('TypeError', false), 'Couldn’t start the microphone. Try again, or reload the page.');+ assert.equal(ui.micErrorText(undefined, true), 'Couldn’t start the microphone. Try again, or reload the page.');+});++// ---------------------------------------------------------------------------------------------------+// 5. Retry only for 429/502/network++test('canRetry: busy, OpenAI failed and no network keep the recording; the rest need a new one', () => {+ assert.equal(ui.canRetry(429, 'busy'), true);+ assert.equal(ui.canRetry(502, 'transcriber_failed'), true);+ assert.equal(ui.canRetry(0, 'network'), true);+ for (const [s, c] of [[413, 'too_large'], [400, 'empty_audio'], [400, 'interrupted'], [415, 'bad_audio_type'], [400, 'bad_lang'], [403, null], [404, null], [409, null]])+ assert.equal(ui.canRetry(s, c), false, `${s} ${c}`);+});++test('transcribe: the raw recording as the body with its type, lang only when given; refusals as sent', async () => {+ reset();+ const blob = new Blob(['x'], { type: 'audio/webm;codecs=opus' });+ server.answers.push([200, { text: 'Book a table for four on Friday at seven.', source: 'openai' }]);+ assert.deepEqual(await ui.transcribe('spc_t', blob, 'en'), { ok: true, text: 'Book a table for four on Friday at seven.' });+ assert.equal(server.posts[0].url, '/api/spaces/spc_t/transcribe?lang=en');+ assert.equal(server.posts[0].type, 'audio/webm;codecs=opus');+ assert.equal(server.posts[0].body, blob);+ server.answers.push([429, { error: 'Other recordings are being turned into text. Try again in a moment.', code: 'busy' }]);+ const r = await ui.transcribe('spc_t', blob, null);+ assert.equal(server.posts[1].url, '/api/spaces/spc_t/transcribe');+ assert.deepEqual(r, { ok: false, status: 429, code: 'busy', error: 'Other recordings are being turned into text. Try again in a moment.', why: null });+ server.answers.push([0]);+ assert.deepEqual(await ui.transcribe('spc_t', blob, null), { ok: false, status: 0, code: 'network', error: ui.NETWORK_ERROR });+});++// ---------------------------------------------------------------------------------------------------+// 6–8. In the real ChatView++test('Desktop: the mic sits between @ and Send, records, and Send waits for dictation; the words land at the caret', async () => {+ reset();+ server.get.spc_a = { available: true, source: 'openai', why: null };+ const sent = [];+ const v = ui.mount(props({ spaceId: 'spc_a', onSendMessage: (t) => sent.push(t) }));+ await settle();+ const tools = [...v.host.querySelectorAll('[data-composer-tools] > button')].map((b) => b.getAttribute('aria-label'));+ assert.deepEqual(tools, ['Attach files', 'Mention a bot', 'Dictate', 'Send']);+ assert.equal(micBtn(v.host).getAttribute('aria-pressed'), 'false');+ assert.equal(micBtn(v.host).title, 'Dictate: speak, then edit before you send');++ const ta = $(v.host, 'textarea[data-composer]');+ ta.focus();+ typeInto(ta, 'Wren, plan the spring newsletter.');+ assert.equal(sendBtn(v.host).disabled, false);++ let release;+ server.hold = new Promise((r) => (release = r));+ server.answers.push([200, { text: 'Use the three customer quotes from last week.', source: 'openai' }]);+ click(micBtn(v.host));+ await settle();+ assert.equal(micBtn(v.host).dataset.mic, 'rec');+ assert.equal(micBtn(v.host).getAttribute('aria-pressed'), 'true');+ assert.equal(micBtn(v.host).title, 'Stop and turn it into text (Esc)');+ assert.equal(line(v.host).dataset.dictationLine, 'recording');+ assert.match(line(v.host).textContent, /Listening0:0\d.*nothing goes to Wren until you press Send/);+ assert.equal(sendBtn(v.host).disabled, true, 'Send is disabled while recording');+ assert.equal(sendBtn(v.host).getAttribute('aria-label'), 'Send (waiting for dictation)');+ assert.equal(sendBtn(v.host).title, 'Waiting for dictation to finish');+ // Enter does not send while dictating+ ui.act(() => ta.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Enter', bubbles: true })));+ assert.equal(sent.length, 0);++ click(micBtn(v.host)); // stop+ await settle(3);+ assert.equal(mic.stopped > 0, true, 'the microphone is released at once');+ assert.equal(micBtn(v.host).dataset.mic, 'busy');+ assert.equal(micBtn(v.host).getAttribute('aria-disabled'), 'true');+ assert.equal(line(v.host).dataset.dictationLine, 'transcribing');+ assert.match(line(v.host).textContent, /Turning speech into text…0:00 recorded/);+ assert.equal(sendBtn(v.host).disabled, true, 'Send is disabled while turning into text');+ assert.equal(server.posts.at(-1).type, 'audio/webm;codecs=opus');++ release();+ await settle();+ assert.equal(ta.value, 'Wren, plan the spring newsletter. Use the three customer quotes from last week.');+ assert.equal(line(v.host).dataset.dictationLine, 'added');+ assert.match(line(v.host).textContent, /Added 8 words\. Read them over, then press Send\./);+ assert.ok($(v.host, '[data-dictation-line] button'), 'Undo shows');+ assert.equal(sendBtn(v.host).disabled, false);+ assert.equal(sendBtn(v.host).getAttribute('aria-label'), 'Send');+ assert.equal(document.activeElement, ta, 'desktop: focus goes to the text, caret after the words');+ assert.equal(ta.selectionStart, ta.value.length);+ assert.match($(v.host, '[data-dictation-announce]').textContent, /Added 8 words to the message\./);+ assert.equal(sent.length, 0, 'nothing went to a bot');++ // Undo removes exactly what was added+ click($(v.host, '[data-dictation-line] button'));+ await settle(3);+ assert.equal(ta.value, 'Wren, plan the spring newsletter.');+ assert.equal(line(v.host), null);+ v.unmount();+});++test('Undo hides once the words were edited, and the line goes on the next keystroke', async () => {+ reset();+ server.get.spc_u = { available: true, source: 'openai', why: null };+ const v = ui.mount(props({ spaceId: 'spc_u' }));+ await settle();+ server.answers.push([200, { text: 'hello there', source: 'openai' }]);+ click(micBtn(v.host));+ await settle();+ click(micBtn(v.host));+ await settle();+ const ta = $(v.host, 'textarea[data-composer]');+ assert.equal(ta.value, 'hello there');+ assert.equal(line(v.host).dataset.dictationLine, 'added');+ v.render(props({ spaceId: 'spc_u' }));+ typeInto(ta, 'hello where');+ assert.equal(line(v.host), null, 'a keystroke clears the Added line');+ v.unmount();+});++test('Esc stops and transcribes; Cancel throws the recording away and says so', async () => {+ reset();+ server.get.spc_e = { available: true, source: 'openai', why: null };+ const v = ui.mount(props({ spaceId: 'spc_e' }));+ await settle();+ server.answers.push([200, { text: 'by Esc', source: 'openai' }]);+ click(micBtn(v.host));+ await settle();+ ui.act(() => document.body.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));+ await settle();+ assert.equal($(v.host, 'textarea[data-composer]').value, 'by Esc');++ const posts = server.posts.length;+ click(micBtn(v.host));+ await settle();+ assert.equal(line(v.host).dataset.dictationLine, 'recording');+ click([...v.host.querySelectorAll('[data-dictation-line] button')].find((b) => b.textContent === 'Cancel'));+ await settle();+ assert.equal(line(v.host), null);+ assert.equal(server.posts.length, posts, 'nothing was sent');+ assert.equal(micBtn(v.host).dataset.mic, 'ready');+ assert.equal($(v.host, '[data-dictation-announce]').textContent, 'Dictation cancelled.');+ assert.equal(document.activeElement, micBtn(v.host));+ v.unmount();+});++test('Errors: 429 keeps the recording for Try again; 413 has only ✕; a blocked microphone says what fixes it', async () => {+ reset();+ server.get.spc_r = { available: true, source: 'openai', why: null };+ const v = ui.mount(props({ spaceId: 'spc_r' }));+ await settle();+ const ta = $(v.host, 'textarea[data-composer]');+ typeInto(ta, 'Typed first.');+ server.answers.push([429, { error: 'Other recordings are being turned into text. Try again in a moment.', code: 'busy' }]);+ click(micBtn(v.host));+ await settle();+ click(micBtn(v.host));+ await settle();+ let l = line(v.host);+ assert.equal(l.dataset.dictationLine, 'bad');+ assert.equal(l.getAttribute('role'), 'alert');+ assert.match(l.textContent, /Other recordings are being turned into text\. Try again in a moment\./);+ assert.equal(ta.value, 'Typed first.', 'what was typed is kept');+ const tryAgain = [...l.querySelectorAll('button')].find((b) => b.textContent.includes('Try again'));+ assert.ok(tryAgain);+ assert.equal(document.activeElement, micBtn(v.host), 'focus returns to the mic');+ const first = server.posts.at(-1).body;+ server.answers.push([200, { text: 'second time lucky', source: 'openai' }]);+ click(tryAgain);+ await settle();+ assert.equal(server.posts.at(-1).body, first, 'Try again sends the same recording');+ assert.equal(ta.value, 'Typed first. second time lucky');++ server.answers.push([413, { error: 'The recording is over 25 MB. Record a shorter message.', code: 'too_large' }]);+ click(micBtn(v.host));+ await settle();+ click(micBtn(v.host));+ await settle();+ l = line(v.host);+ assert.deepEqual([...l.querySelectorAll('button')].map((b) => b.getAttribute('aria-label') ?? b.textContent), ['Dismiss']);+ click(l.querySelector('button'));+ assert.equal(line(v.host), null);++ server.answers.push([200, { text: ' ', source: 'openai' }]);+ click(micBtn(v.host));+ await settle();+ click(micBtn(v.host));+ await settle();+ assert.equal(line(v.host).dataset.dictationLine, 'warn');+ assert.match(line(v.host).textContent, /Didn’t catch any words/);++ mic.refuse = 'NotAllowedError';+ click(micBtn(v.host));+ await settle();+ l = line(v.host);+ assert.equal(l.dataset.dictationLine, 'warn');+ assert.match(l.textContent, /Allow it from the icon at the left of the address bar/);+ assert.equal(micBtn(v.host).dataset.mic, 'ready');+ v.unmount();+});++test('409 no_transcriber: the mic turns muted and the popover opens with the server’s why; typing is untouched', async () => {+ reset();+ server.get.spc_n = { available: true, source: 'openai', why: null };+ let opened = 0;+ const v = ui.mount(props({ spaceId: 'spc_n', onOpenAccounts: () => opened++ }));+ await settle();+ const ta = $(v.host, 'textarea[data-composer]');+ typeInto(ta, 'Keep me.');+ const why = 'The OpenAI API is turned off in Apps & accounts. Turn it on to dictate.';+ server.answers.push([409, { error: why, code: 'no_transcriber', why }]);+ click(micBtn(v.host));+ await settle();+ click(micBtn(v.host));+ await settle();+ assert.equal(ta.value, 'Keep me.');+ assert.equal(line(v.host), null, 'no line: the popover says it');+ assert.equal(micBtn(v.host).dataset.mic, 'muted');+ assert.equal(micBtn(v.host).getAttribute('aria-label'), 'Dictate (not set up)');+ assert.equal(micBtn(v.host).getAttribute('aria-expanded'), 'true');+ const pop = $(v.host, '[data-dictation-popover]');+ assert.ok(pop);+ assert.equal(pop.getAttribute('role'), 'dialog');+ assert.match(pop.textContent, /Dictation isn’t set up in this space/);+ assert.ok(pop.textContent.includes(why));+ assert.equal(document.activeElement.textContent, 'Open Apps & accounts');+ click([...pop.querySelectorAll('button')].find((b) => b.textContent === 'Open Apps & accounts'));+ assert.equal(opened, 1);+ assert.equal($(v.host, '[data-dictation-popover]'), null);+ v.unmount();+});++test('Not set up: the muted mic opens the popover; Esc closes it to the mic; Hide the mic hides it until a key arrives', async () => {+ reset();+ server.get.spc_off = { available: false, source: null, why: 'Add an OpenAI API key in Apps & accounts to dictate.' };+ const v = ui.mount(props({ spaceId: 'spc_off', onOpenAccounts: () => {} }));+ await settle();+ assert.equal(micBtn(v.host).dataset.mic, 'muted');+ assert.equal(micBtn(v.host).disabled, false, 'focusable and pressable');+ assert.equal(micBtn(v.host).getAttribute('aria-haspopup'), 'dialog');+ click(micBtn(v.host));+ await settle(3);+ assert.ok($(v.host, '[data-dictation-popover]'));+ assert.equal(mic.streams, mic.streams, 'no microphone asked for');+ ui.act(() => document.body.dispatchEvent(new window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true })));+ assert.equal($(v.host, '[data-dictation-popover]'), null);+ assert.equal(document.activeElement, micBtn(v.host));+ click(micBtn(v.host));+ await settle(3);+ click([...$(v.host, '[data-dictation-popover]').querySelectorAll('button')].find((b) => b.textContent === 'Hide the mic'));+ await settle(3);+ assert.equal(micBtn(v.host), null);+ assert.equal(localStorage.getItem('kwnt:dictation-hidden:spc_off'), '1');+ assert.equal($(v.host, '[data-dictation-announce]').textContent, 'Mic hidden. It comes back when dictation is set up.');+ // a key gets added: the next GET says yes, and the mic is back+ server.get.spc_off = { available: true, source: 'openai', why: null };+ ui.refreshDictation();+ await settle();+ assert.equal(micBtn(v.host)?.dataset.mic, 'ready');+ assert.equal(localStorage.getItem('kwnt:dictation-hidden:spc_off'), null);+ v.unmount();+});++test('No mic when the GET fails or 404s, or the browser can’t record', async () => {+ reset();+ server.get.spc_down = 'down';+ let v = ui.mount(props({ spaceId: 'spc_down' }));+ await settle();+ assert.equal(micBtn(v.host), null);+ assert.equal(line(v.host), null, 'no error line: nothing the person did');+ v.unmount();+ v = ui.mount(props({ spaceId: 'spc_missing' }));+ await settle();+ assert.equal(micBtn(v.host), null);+ v.unmount();+ server.get.spc_norec = { available: true, source: 'openai', why: null };+ const keep = dom.window.MediaRecorder;+ delete dom.window.MediaRecorder;+ v = ui.mount(props({ spaceId: 'spc_norec' }));+ await settle();+ assert.equal(micBtn(v.host), null);+ v.unmount();+ dom.window.MediaRecorder = keep;+});++test('Phone at rest: the mic takes Send’s slot only while it shows; stacked brings Send back', async () => {+ reset();+ media.phone = true;+ media.coarse = true;+ server.get.spc_p = { available: true, source: 'openai', why: null };+ let v = ui.mount(props({ spaceId: 'spc_p' }));+ await settle();+ const form = $(v.host, 'form[data-composer-form]');+ assert.equal(form.dataset.stacked, 'false');+ assert.ok(micBtn(v.host));+ assert.equal(sendBtn(v.host), null, 'at rest: no Send, the mic is in its slot');+ const ta = $(v.host, 'textarea[data-composer]');+ typeInto(ta, 'Hi');+ assert.equal(form.dataset.stacked, 'true');+ const tools = [...v.host.querySelectorAll('[data-composer-tools] > button')].map((b) => b.getAttribute('aria-label'));+ assert.deepEqual(tools, ['Attach files', 'Mention a bot', 'Dictate', 'Send']);+ v.unmount();+ // No mic (GET failed): Send keeps its slot at rest+ server.get.spc_p2 = 'down';+ v = ui.mount(props({ spaceId: 'spc_p2' }));+ await settle();+ assert.equal(micBtn(v.host), null);+ assert.ok(sendBtn(v.host), 'Send stays when there is no mic');+ v.unmount();+});++test('Phone: dictating does not focus the text (no keyboard); the words land and focus stays on the mic', async () => {+ reset();+ media.phone = true;+ media.coarse = true;+ server.get.spc_ph = { available: true, source: 'openai', why: null };+ const v = ui.mount(props({ spaceId: 'spc_ph' }));+ await settle();+ server.answers.push([200, { text: 'from the phone', source: 'openai' }]);+ micBtn(v.host).focus();+ click(micBtn(v.host));+ await settle();+ assert.equal($(v.host, 'textarea[data-composer]').placeholder, 'Speak now…');+ assert.notEqual(document.activeElement, $(v.host, 'textarea[data-composer]'));+ assert.ok(!/nothing goes to/.test(line(v.host).textContent), 'the long note is desktop only');+ click(micBtn(v.host));+ await settle();+ assert.equal($(v.host, 'textarea[data-composer]').value, 'from the phone');+ assert.equal(document.activeElement, micBtn(v.host));+ assert.ok(sendBtn(v.host), 'it has words now, so it stacks and Send is back');+ v.unmount();+});++test('Leaving the chat while recording stops it, discards it and says so', async () => {+ reset();+ server.get.spc_l = { available: true, source: 'openai', why: null };+ const toasts = [];+ const v = ui.mount(props({ spaceId: 'spc_l', onToast: (t) => toasts.push(t) }));+ await settle();+ click(micBtn(v.host));+ await settle();+ const posts = server.posts.length;+ const stopped = mic.stopped;+ v.render(props({ spaceId: 'spc_l', contextKey: 'k:ola', onToast: (t) => toasts.push(t) }));+ await settle();+ assert.deepEqual(toasts, ['Dictation stopped: you left the chat.']);+ assert.equal(server.posts.length, posts);+ assert.ok(mic.stopped > stopped);+ assert.equal(line(v.host), null);+ v.unmount();+});++test('Wiring: App passes the real space id and a toast, and asks again when Space settings close', () => {+ const app = readFileSync(new URL('../src/App.tsx', import.meta.url), 'utf8');+ const at = app.indexOf('const chat = (');+ const site = app.slice(at, app.indexOf('/>', app.indexOf('<ChatView', at)));+ assert.match(site, /spaceId=\{space\.id\}/);+ assert.match(site, /onToast=\{pushToast\}/);+ const close = app.slice(app.indexOf('const closeSpaceSettings'), app.indexOf('const closeSpaceSettings') + 500);+ assert.match(close, /refreshDictation\(\)/);+});++test('Mira round 1 fixes: transcribing wraps, phone 6 px gaps, desktop one-line error centred, New tag hides under the popover', () => {+ const mic = readFileSync(new URL('../src/components/DictationMic.tsx', import.meta.url), 'utf8');+ const chat = readFileSync(new URL('../src/components/ChatView.tsx', import.meta.url), 'utf8');+ // 1. the label wraps (no truncate) and the time never breaks+ assert.match(mic, /<b className="font-semibold text-zinc-100 min-w-0">Turning speech into text…<\/b>/);+ assert.match(mic, /tabular-nums text-zinc-400 flex-none whitespace-nowrap">\{clock\(l\.seconds\)\} recorded/);+ // 2. ml-1.5 on phone mic and phone Send only; desktop sizes unchanged+ assert.match(mic, /const size = phone \? 'w-11 h-11 ml-1\.5 [^']*' : 'w-11 h-11 sm:w-9 sm:h-9 focus-visible:outline-sky-400'/);+ assert.match(chat, /\$\{phone \? 'w-11 h-11 ml-1\.5 focus-visible:outline-\[#b8adff\]' : 'w-11 h-11 sm:w-9 sm:h-9 focus-visible:outline-sky-300'\}/);+ // 3. bad and warn: desktop text pt-[5px], icon mt-[7px]; phone keeps mt-0.5+ assert.equal((mic.match(/\$\{phone \? 'mt-0\.5' : 'mt-\[7px\]'\}/g) || []).length, 2);+ assert.equal((mic.match(/\$\{phone \? '' : 'pt-\[5px\]'\}/g) || []).length, 2);+ // 4. both mention New tags hide while the setup popover is open+ assert.equal((chat.match(/\$\{dict\.popOpen \? 'hidden' : ''\}/g) || []).length, 2);+});