Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(desktop): voice typing in the chat, code and bot boxes and brain fields

Salman Qureshi73e9b834e17c
diff --git a/apps/desktop/src-tauri/Entitlements.plist b/apps/desktop/src-tauri/Entitlements.plist
new file mode 100644
index 00000000..8160ed58
--- /dev/null
+++ b/apps/desktop/src-tauri/Entitlements.plist
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- Hardened runtime: the microphone, for dictation in text boxes. -->
+ <key>com.apple.security.device.audio-input</key>
+ <true/>
+</dict>
+</plist>
diff --git a/apps/desktop/src-tauri/Info.plist b/apps/desktop/src-tauri/Info.plist
new file mode 100644
index 00000000..70b80958
--- /dev/null
+++ b/apps/desktop/src-tauri/Info.plist
@@ -0,0 +1,9 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
+<plist version="1.0">
+<dict>
+ <!-- Merged into the app's Info.plist by Tauri (and embedded in dev builds). -->
+ <key>NSMicrophoneUsageDescription</key>
+ <string>Mercury listens only after you click the mic in a text box, to type what you say.</string>
+</dict>
+</plist>
diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json
index bc88aca5..476aa273 100644
--- a/apps/desktop/src-tauri/tauri.conf.json
+++ b/apps/desktop/src-tauri/tauri.conf.json
@@ -64,7 +64,8 @@
"width": 660,
"height": 400
}
- }
+ },
+ "entitlements": "./Entitlements.plist"
},
"windows": {
"webviewInstallMode": {
diff --git a/apps/desktop/src/api/models.ts b/apps/desktop/src/api/models.ts
index f33b7f46..37c552bb 100644
--- a/apps/desktop/src/api/models.ts
+++ b/apps/desktop/src/api/models.ts
@@ -1,4 +1,4 @@
-import { http } from "./client";
+import { http, request } from "./client";
import type { PluginItem } from "./types";
/** Model providers and gateways (GET/POST /api/providers*), voice key checks, and Optimus voice settings. */
@@ -132,3 +132,14 @@ export const cloudApi = {
signIn: () => http.get<CloudSignIn | { status: "none" }>("/api/cloud/signin"),
cancelSignIn: () => http.delete<{ ok: boolean }>("/api/cloud/signin"),
};
+
+/** Dictation: GET tells whether a speech service is set up; POST sends raw audio and gets text back. */
+export const transcribeApi = {
+ status: () => http.get<{ available: boolean; engine: string | null }>("/api/transcribe"),
+ send: (audio: Blob, language?: string) =>
+ request<{ text: string; engine: string }>(`/api/transcribe${language ? `?language=${encodeURIComponent(language)}` : ""}`, {
+ method: "POST",
+ body: audio,
+ headers: { "Content-Type": audio.type || "audio/webm" },
+ }),
+};
diff --git a/apps/desktop/src/components/dictation/Dictation.tsx b/apps/desktop/src/components/dictation/Dictation.tsx
new file mode 100644
index 00000000..45b61ae9
--- /dev/null
+++ b/apps/desktop/src/components/dictation/Dictation.tsx
@@ -0,0 +1,113 @@
+import { ArrowUp, Check, Mic, X } from "lucide-react";
+import { useUi } from "~/app/store";
+import { Button } from "~/components/ui/Button";
+import { Spinner } from "~/components/ui/bits";
+import { Tooltip } from "~/components/ui/Tooltip";
+import { cx } from "~/lib/cx";
+import { formatClock, useDictation, type FinishMode } from "./useDictation";
+
+/**
+ * Voice typing, ChatGPT-style. Click the mic and talk: the box shows your
+ * voice as a moving wave with a timer. ✓ puts the words in the box, ↑ sends
+ * them straight away (where the box can send), × throws the take away.
+ * With no speech service set up, the mic says how to add one.
+ */
+
+export type Dictation = ReturnType<typeof useDictation>;
+
+export function Waveform({ levels, className }: { levels: number[]; className?: string }) {
+ return (
+ <div className={cx("flex h-7 min-w-0 flex-1 items-center gap-[3px] overflow-hidden", className)} aria-hidden="true">
+ {levels.map((l, i) => (
+ <span key={i} className="w-[3px] shrink-0 rounded-full bg-ink/70 transition-[height] duration-75" style={{ height: `${Math.max(3, Math.round(l * 26))}px`, opacity: 0.35 + l * 0.65 }} />
+ ))}
+ </div>
+ );
+}
+
+/** The mic button in its idle / starting / transcribing states. */
+export function MicButton({ d, disabled, size = "md" }: { d: Dictation; disabled?: boolean; size?: "sm" | "md" }) {
+ const busy = d.phase === "starting" || d.phase === "transcribing";
+ return (
+ <Tooltip label={d.phase === "transcribing" ? "Turning speech into text…" : "Dictate"} side="top">
+ <Button type="button" variant="ghost" size={size} icon disabled={disabled || busy} onClick={() => void d.start()} aria-label="Dictate" className="!rounded-full">
+ {busy ? <Spinner size={size === "sm" ? 12 : 15} /> : <Mic size={size === "sm" ? 14 : 17} />}
+ </Button>
+ </Tooltip>
+ );
+}
+
+/** While recording: wave, timer, and what to do with the take. */
+export function RecordingBar({ d, canSend, className }: { d: Dictation; canSend: boolean; className?: string }) {
+ return (
+ <div className={cx("flex min-w-0 items-center gap-2", className)} role="group" aria-label="Recording">
+ <span className="h-2 w-2 shrink-0 animate-pulse rounded-full bg-red" aria-hidden="true" />
+ <Waveform levels={d.levels} />
+ <span className="shrink-0 font-mono text-xs tabular-nums text-ink3" aria-live="off">{formatClock(d.seconds)}</span>
+ <Tooltip label="Discard" shortcut="esc" side="top">
+ <Button type="button" variant="ghost" size="md" icon onClick={() => d.finish("cancel")} aria-label="Discard recording" className="!rounded-full"><X size={16} /></Button>
+ </Tooltip>
+ <Tooltip label="Stop and put the words in the box" side="top">
+ <Button type="button" variant={canSend ? "outline" : "primary"} size="md" icon onClick={() => d.finish("insert")} aria-label="Stop and insert text" className="!rounded-full"><Check size={16} strokeWidth={2.4} /></Button>
+ </Tooltip>
+ {canSend && (
+ <Tooltip label="Stop and send" shortcut="↵" side="top">
+ <Button type="button" variant="primary" size="md" icon onClick={() => d.finish("send")} aria-label="Stop and send" className="!rounded-full"><ArrowUp size={17} strokeWidth={2.4} /></Button>
+ </Tooltip>
+ )}
+ </div>
+ );
+}
+
+/** No speech service, a denied mic, or a failed transcription: one line and a way forward. */
+export function DictationNotice({ d, className }: { d: Dictation; className?: string }) {
+ const openSettings = useUi((s) => s.openSettings);
+ if (d.phase !== "needs-setup" && d.phase !== "error") return null;
+ return (
+ <div className={cx("flex flex-wrap items-center gap-2 rounded-lg border border-amber/40 bg-amber/[0.06] px-3 py-2 text-xs text-ink2", className)} role="alert">
+ <Mic size={13} className="shrink-0 text-amber" />
+ <span className="min-w-0 flex-1">
+ {d.phase === "needs-setup"
+ ? "Voice typing needs a speech service. Add an OpenAI key under Models, or a Deepgram or ElevenLabs key under Voice."
+ : d.error}
+ </span>
+ {d.phase === "needs-setup" && (
+ <>
+ <Button type="button" size="sm" variant="primary" onClick={() => { d.dismiss(); openSettings("models"); }}>Add OpenAI key</Button>
+ <Button type="button" size="sm" variant="outline" onClick={() => { d.dismiss(); openSettings("voice"); }}>Voice settings</Button>
+ </>
+ )}
+ <button type="button" onClick={d.dismiss} className="text-ink4 hover:text-ink" aria-label="Dismiss"><X size={13} /></button>
+ </div>
+ );
+}
+
+/**
+ * For any text field: a small mic in its corner. Words are added at the end
+ * of what's there. Put it inside a `relative` wrapper around the field.
+ */
+export function FieldMic({ value, onChange, disabled, className }: { value: string; onChange: (next: string) => void; disabled?: boolean; className?: string }) {
+ const d = useDictation((text) => onChange(joinText(value, text)));
+ if (d.phase === "recording") {
+ return (
+ <div className={cx("absolute inset-x-1 bottom-1 z-10 rounded-full border border-line bg-surface px-2 py-0.5 shadow-md", className)}>
+ <RecordingBar d={d} canSend={false} />
+ </div>
+ );
+ }
+ return (
+ <>
+ <div className={cx("absolute bottom-1 right-1", className)}><MicButton d={d} disabled={disabled} size="sm" /></div>
+ {(d.phase === "needs-setup" || d.phase === "error") && <DictationNotice d={d} className="absolute inset-x-0 top-full z-20 mt-1" />}
+ </>
+ );
+}
+
+/** Append dictated words to existing text with sensible spacing. */
+export function joinText(existing: string, added: string): string {
+ if (!existing.trim()) return added;
+ return /\s$/.test(existing) ? existing + added : `${existing} ${added}`;
+}
+
+export type { FinishMode };
+export { useDictation };
diff --git a/apps/desktop/src/components/dictation/dictation.test.ts b/apps/desktop/src/components/dictation/dictation.test.ts
new file mode 100644
index 00000000..8b89e2c5
--- /dev/null
+++ b/apps/desktop/src/components/dictation/dictation.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+import { joinText } from "./Dictation";
+import { formatClock, micErrorText, pickMimeType } from "./useDictation";
+
+describe("dictation", () => {
+ it("adds spoken words after what's typed, with one space", () => {
+ expect(joinText("", "hello")).toBe("hello");
+ expect(joinText("Remind me", "to call Heer")).toBe("Remind me to call Heer");
+ expect(joinText("Line one\n", "line two")).toBe("Line one\nline two");
+ });
+ it("records in the best format the webview supports", () => {
+ expect(pickMimeType((t) => t.startsWith("audio/mp4"))).toBe("audio/mp4;codecs=mp4a.40.2");
+ expect(pickMimeType((t) => t === "audio/webm;codecs=opus")).toBe("audio/webm;codecs=opus");
+ expect(pickMimeType(() => false)).toBe("");
+ });
+ it("explains microphone failures in plain words", () => {
+ expect(micErrorText(new DOMException("x", "NotAllowedError"))).toMatch(/Privacy & Security → Microphone/);
+ expect(micErrorText(new DOMException("x", "NotFoundError"))).toMatch(/No microphone/);
+ });
+ it("shows the timer as m:ss", () => {
+ expect(formatClock(0)).toBe("0:00");
+ expect(formatClock(75)).toBe("1:15");
+ });
+});
diff --git a/apps/desktop/src/components/dictation/useDictation.ts b/apps/desktop/src/components/dictation/useDictation.ts
new file mode 100644
index 00000000..b7e7f9b0
--- /dev/null
+++ b/apps/desktop/src/components/dictation/useDictation.ts
@@ -0,0 +1,165 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { ApiError } from "~/api/client";
+import { transcribeApi } from "~/api/models";
+
+/**
+ * Record from the microphone, then turn it into text with Mercury's speech
+ * service. One recording at a time across the app.
+ *
+ * idle → (start) → recording → (finish) → transcribing → idle, text delivered
+ * → (cancel) → idle, nothing kept
+ *
+ * `needs-setup` when no speech service is configured (the button explains
+ * how to add one); `error` for a denied microphone or a failed transcription.
+ */
+
+export type DictationPhase = "idle" | "starting" | "recording" | "transcribing" | "needs-setup" | "error";
+export type FinishMode = "insert" | "send";
+
+/** Longest single dictation; it stops and transcribes by itself after this. */
+const MAX_SECONDS = 5 * 60;
+const BARS = 48;
+
+let activeStop: (() => void) | null = null;
+let availability: { at: number; available: boolean } | null = null;
+
+/** Best recording format this webview supports (WebKit records mp4, Chromium webm). */
+export function pickMimeType(isSupported: (t: string) => boolean = (t) => typeof MediaRecorder !== "undefined" && MediaRecorder.isTypeSupported(t)): string {
+ for (const t of ["audio/webm;codecs=opus", "audio/webm", "audio/mp4;codecs=mp4a.40.2", "audio/mp4", "audio/ogg;codecs=opus"]) if (isSupported(t)) return t;
+ return "";
+}
+
+/** Plain words for microphone failures. */
+export function micErrorText(err: unknown): string {
+ const name = err instanceof DOMException ? err.name : err instanceof Error ? err.name : "";
+ if (name === "NotAllowedError" || name === "SecurityError") return "Mercury isn't allowed to use the microphone. Allow it in System Settings → Privacy & Security → Microphone, then try again.";
+ if (name === "NotFoundError" || name === "OverconstrainedError") return "No microphone found. Plug one in or pick one in your system's sound settings.";
+ if (name === "NotReadableError") return "The microphone is busy in another app.";
+ return err instanceof Error ? err.message : String(err);
+}
+
+export function useDictation(onText: (text: string, mode: FinishMode) => void) {
+ const [phase, setPhase] = useState<DictationPhase>("idle");
+ const [error, setError] = useState<string | null>(null);
+ const [levels, setLevels] = useState<number[]>(() => Array(BARS).fill(0));
+ const [seconds, setSeconds] = useState(0);
+ const rec = useRef<{ recorder: MediaRecorder; stream: MediaStream; ctx: AudioContext; chunks: Blob[]; timer: number; raf: number; mode: FinishMode | "cancel" } | null>(null);
+ const onTextRef = useRef(onText);
+ onTextRef.current = onText;
+ // A stable "cancel me" for the one-recording-at-a-time rule.
+ const finishRef = useRef<(mode: FinishMode | "cancel") => void>(() => {});
+ const stopSelf = useRef(() => finishRef.current("cancel")).current;
+
+ const teardown = useCallback(() => {
+ const r = rec.current;
+ if (!r) return;
+ window.clearInterval(r.timer);
+ cancelAnimationFrame(r.raf);
+ r.stream.getTracks().forEach((t) => t.stop());
+ void r.ctx.close().catch(() => {});
+ rec.current = null;
+ if (activeStop === stopSelf) activeStop = null;
+ }, [stopSelf]);
+
+ const finish = useCallback((mode: FinishMode | "cancel") => {
+ const r = rec.current;
+ if (!r) return;
+ r.mode = mode;
+ if (r.recorder.state !== "inactive") r.recorder.stop();
+ else teardown();
+ }, [teardown]);
+ finishRef.current = finish;
+
+ const start = useCallback(async () => {
+ if (rec.current) return;
+ setError(null);
+ setPhase("starting");
+ // Is there a speech service? Asked once a minute at most.
+ try {
+ if (!availability || Date.now() - availability.at > 60_000) {
+ const s = await transcribeApi.status();
+ availability = { at: Date.now(), available: s.available };
+ }
+ if (!availability.available) { setPhase("needs-setup"); return; }
+ } catch {
+ // Older Mercury without dictation, or offline.
+ setError("This Mercury can't transcribe speech yet. Update Mercury to use voice typing.");
+ setPhase("error");
+ return;
+ }
+ activeStop?.();
+ let stream: MediaStream;
+ try {
+ stream = await navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true, noiseSuppression: true, autoGainControl: true } });
+ } catch (err) {
+ setError(micErrorText(err));
+ setPhase("error");
+ return;
+ }
+ const mimeType = pickMimeType();
+ const recorder = new MediaRecorder(stream, mimeType ? { mimeType, audioBitsPerSecond: 48_000 } : undefined);
+ const ctx = new AudioContext();
+ const analyser = ctx.createAnalyser();
+ analyser.fftSize = 512;
+ ctx.createMediaStreamSource(stream).connect(analyser);
+ const buf = new Uint8Array(analyser.fftSize);
+ const started = Date.now();
+ const r = { recorder, stream, ctx, chunks: [] as Blob[], timer: 0, raf: 0, mode: "insert" as FinishMode | "cancel" };
+ rec.current = r;
+ activeStop = stopSelf;
+
+ let lastPush = 0;
+ const tick = () => {
+ analyser.getByteTimeDomainData(buf);
+ let peak = 0;
+ for (let i = 0; i < buf.length; i++) peak = Math.max(peak, Math.abs(buf[i] - 128));
+ const now = performance.now();
+ if (now - lastPush > 70) {
+ lastPush = now;
+ const level = Math.min(1, (peak / 128) * 2.2);
+ setLevels((l) => [...l.slice(1), level]);
+ }
+ r.raf = requestAnimationFrame(tick);
+ };
+ r.raf = requestAnimationFrame(tick);
+ r.timer = window.setInterval(() => {
+ const s = Math.floor((Date.now() - started) / 1000);
+ setSeconds(s);
+ if (s >= MAX_SECONDS) finish("insert");
+ }, 250);
+
+ recorder.ondataavailable = (e) => { if (e.data.size) r.chunks.push(e.data); };
+ recorder.onstop = async () => {
+ const mode = r.mode;
+ const blob = new Blob(r.chunks, { type: recorder.mimeType || mimeType || "audio/webm" });
+ teardown();
+ setLevels(Array(BARS).fill(0));
+ setSeconds(0);
+ if (mode === "cancel") { setPhase("idle"); return; }
+ setPhase("transcribing");
+ try {
+ // No language hint: the service detects it, which handles mixed Urdu/Hindi/English best.
+ const { text } = await transcribeApi.send(blob);
+ setPhase("idle");
+ if (text.trim()) onTextRef.current(text.trim(), mode);
+ else { setError("Didn't catch anything. Try again a little closer to the mic."); setPhase("error"); }
+ } catch (err) {
+ if (err instanceof ApiError && err.data.needs === "speech") { availability = null; setPhase("needs-setup"); return; }
+ setError(err instanceof Error ? err.message : String(err));
+ setPhase("error");
+ }
+ };
+ recorder.start(1000);
+ setSeconds(0);
+ setPhase("recording");
+ }, [finish, teardown, stopSelf]);
+
+ useEffect(() => () => { const r = rec.current; if (r) { r.mode = "cancel"; try { r.recorder.stop(); } catch { /* already stopped */ } teardown(); } }, [teardown]);
+
+ const dismiss = useCallback(() => { setError(null); setPhase("idle"); }, []);
+ return { phase, error, levels, seconds, start, finish, dismiss };
+}
+
+export function formatClock(s: number): string {
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
+}
diff --git a/apps/desktop/src/views/bots/BotsView.tsx b/apps/desktop/src/views/bots/BotsView.tsx
index 957343eb..1438db8b 100644
--- a/apps/desktop/src/views/bots/BotsView.tsx
+++ b/apps/desktop/src/views/bots/BotsView.tsx
@@ -1,5 +1,6 @@
import { ChevronDown, Play, RefreshCw, Square, Trash2 } from "lucide-react";
-import { useEffect, useMemo, useState } from "react";
+import { DictationNotice, MicButton, RecordingBar, joinText, useDictation } from "~/components/dictation/Dictation";
+import { useEffect, useMemo, useRef, useState } from "react";
import { cx } from "~/lib/cx";
import * as api from "~/api/mercury";
import type { BotManifest, BotStatus } from "~/api/types";
@@ -296,8 +297,14 @@ function BotBody({ id, status }: { id: string; status: BotStatus | null }) {
const [message, setMessage] = useState("");
const [note, setNote] = useState<string | null>(null);
useEffect(() => { setNote(null); setMessage(""); }, [id]);
- async function send() {
- const text = message.trim();
+ const messageRef = useRef(message);
+ messageRef.current = message;
+ const dictation = useDictation((spoken, mode) => {
+ const next = joinText(messageRef.current, spoken);
+ if (mode === "send") void send(next); else setMessage(next);
+ });
+ async function send(override?: string) {
+ const text = (override ?? message).trim();
if (!text) return;
try {
const res = await api.bots.message(id, text);
@@ -312,10 +319,16 @@ function BotBody({ id, status }: { id: string; status: BotStatus | null }) {
<>
<div className="flex flex-col gap-2">
<SectionTitle>Tell {bot.fleetRole === "lead" ? "the fleet" : "it"} something</SectionTitle>
- <div className="flex gap-2">
- <Input value={message} onChange={(e) => setMessage(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") void send(); }} placeholder={`Message ${bot.name}…`} className="h-10 text-base" />
- <Button variant="primary" size="lg" onClick={() => void send()} disabled={!message.trim()}>Send</Button>
- </div>
+ {dictation.phase === "recording" ? (
+ <div className="rounded-full border border-line bg-surface px-3 py-1"><RecordingBar d={dictation} canSend /></div>
+ ) : (
+ <div className="flex items-center gap-2">
+ <Input value={message} onChange={(e) => setMessage(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter") void send(); }} placeholder={`Message ${bot.name}…`} className="h-10 text-base" />
+ <MicButton d={dictation} />
+ <Button variant="primary" size="lg" onClick={() => void send()} disabled={!message.trim()}>Send</Button>
+ </div>
+ )}
+ <DictationNotice d={dictation} />
{note && <p className="text-sm text-ink3">{note}</p>}
</div>
{bot.schedules && bot.schedules.length > 0 && (
diff --git a/apps/desktop/src/views/brain/Memories.tsx b/apps/desktop/src/views/brain/Memories.tsx
index e8099d63..a1e429a4 100644
--- a/apps/desktop/src/views/brain/Memories.tsx
+++ b/apps/desktop/src/views/brain/Memories.tsx
@@ -1,4 +1,5 @@
import { Plus } from "lucide-react";
+import { FieldMic } from "~/components/dictation/Dictation";
import { useCallback, useEffect, useRef, useState } from "react";
import { brain, MEMORY_TYPES, type BrainMemory } from "~/api/brain";
import { Button } from "~/components/ui/Button";
@@ -106,8 +107,8 @@ function MemoryRow({ m, focused, onRemoved, onSaved }: { m: BrainMemory; focused
</div>
{editing ? (
<div className="mt-2 flex flex-col gap-2">
- <textarea value={summary} onChange={(e) => setSummary(e.target.value)} rows={2} className="w-full rounded-md border border-line bg-bg px-3 py-2 text-base text-ink focus:border-accent/60" aria-label="Memory" />
- <textarea value={detail} onChange={(e) => setDetail(e.target.value)} rows={2} placeholder="Detail (optional)" className="w-full rounded-md border border-line bg-bg px-3 py-2 text-sm text-ink2 focus:border-accent/60" aria-label="Detail" />
+ <div className="relative"><textarea value={summary} onChange={(e) => setSummary(e.target.value)} rows={2} className="w-full rounded-md border border-line bg-bg py-2 pl-3 pr-10 text-base text-ink focus:border-accent/60" aria-label="Memory" /><FieldMic value={summary} onChange={setSummary} /></div>
+ <div className="relative"><textarea value={detail} onChange={(e) => setDetail(e.target.value)} rows={2} placeholder="Detail (optional)" className="w-full rounded-md border border-line bg-bg py-2 pl-3 pr-10 text-sm text-ink2 focus:border-accent/60" aria-label="Detail" /><FieldMic value={detail} onChange={setDetail} /></div>
<div className="flex justify-end gap-2"><Button size="sm" variant="ghost" onClick={() => setEditing(false)}>Cancel</Button><Button size="sm" variant="primary" loading={busy} disabled={!summary.trim()} onClick={() => void save()}>Save</Button></div>
</div>
) : (
diff --git a/apps/desktop/src/views/brain/PersonCard.tsx b/apps/desktop/src/views/brain/PersonCard.tsx
index 951efc14..ab445345 100644
--- a/apps/desktop/src/views/brain/PersonCard.tsx
+++ b/apps/desktop/src/views/brain/PersonCard.tsx
@@ -7,6 +7,7 @@ import { Field, Input } from "~/components/ui/Input";
import { Badge, Segmented, Spinner } from "~/components/ui/bits";
import { ConfirmButton } from "~/components/ui/kit";
import { cx } from "~/lib/cx";
+import { FieldMic } from "~/components/dictation/Dictation";
/**
* A person's contact card: view, edit (name, person or pet, relationship,
@@ -182,7 +183,7 @@ function EditForm({ person, onCancel, onSaved }: { person: BrainPerson; onCancel
<Button type="button" size="sm" variant="outline" onClick={() => void save(true)}>Move it to {name.trim() || person.name}</Button>
</div>
)}
- <Field label="About" htmlFor="pc-sum"><textarea id="pc-sum" value={summary} onChange={(e) => setSummary(e.target.value)} rows={2} className="w-full rounded-md border border-line bg-surface px-3 py-2 text-sm text-ink focus:border-accent/60" /></Field>
+ <Field label="About" htmlFor="pc-sum"><div className="relative"><textarea id="pc-sum" value={summary} onChange={(e) => setSummary(e.target.value)} rows={2} className="w-full rounded-md border border-line bg-surface py-2 pl-3 pr-10 text-sm text-ink focus:border-accent/60" /><FieldMic value={summary} onChange={setSummary} /></div></Field>
<div className="grid grid-cols-2 gap-3">
<Field label="Phone" htmlFor="pc-phone"><Input id="pc-phone" value={meta.phone ?? ""} onChange={set("phone")} /></Field>
<Field label="Email" htmlFor="pc-email"><Input id="pc-email" value={meta.email ?? ""} onChange={set("email")} /></Field>
@@ -192,7 +193,7 @@ function EditForm({ person, onCancel, onSaved }: { person: BrainPerson; onCancel
<Field label="Role" htmlFor="pc-role"><Input id="pc-role" value={meta.role ?? ""} onChange={set("role")} /></Field>
</div>
<Field label="Links (one per line)" htmlFor="pc-links"><textarea id="pc-links" value={links} onChange={(e) => setLinks(e.target.value)} rows={2} className="w-full rounded-md border border-line bg-surface px-3 py-2 font-mono text-xs text-ink focus:border-accent/60" /></Field>
- <Field label="Notes" htmlFor="pc-notes"><textarea id="pc-notes" value={meta.notes ?? ""} onChange={set("notes")} rows={3} className="w-full rounded-md border border-line bg-surface px-3 py-2 text-sm text-ink focus:border-accent/60" /></Field>
+ <Field label="Notes" htmlFor="pc-notes"><div className="relative"><textarea id="pc-notes" value={meta.notes ?? ""} onChange={set("notes")} rows={3} className="w-full rounded-md border border-line bg-surface py-2 pl-3 pr-10 text-sm text-ink focus:border-accent/60" /><FieldMic value={meta.notes ?? ""} onChange={(v) => setMeta((m) => ({ ...m, notes: v }))} /></div></Field>
{error && <p className="text-sm text-red">{error}</p>}
<div className="flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={onCancel}>Cancel</Button>
diff --git a/apps/desktop/src/views/chat/Composer.tsx b/apps/desktop/src/views/chat/Composer.tsx
index 9cc238bc..fcb55f3a 100644
--- a/apps/desktop/src/views/chat/Composer.tsx
+++ b/apps/desktop/src/views/chat/Composer.tsx
@@ -9,11 +9,12 @@ import { useConversation, useConversationStore, type Surface } from "~/app/conve
import { Button } from "~/components/ui/Button";
import { Menu, MenuItem, MenuLabel, MenuSeparator } from "~/components/ui/Menu";
import { Tooltip } from "~/components/ui/Tooltip";
+import { DictationNotice, MicButton, RecordingBar, joinText, useDictation } from "~/components/dictation/Dictation";
/**
* One box. Enter sends, Shift+Enter breaks a line, Esc clears. Photos and
* PDFs come in by the paperclip, paste or drag-and-drop (up to 4, the
- * runtime's limit). Below: the model and Ask Me / Allow All, one click each.
+ * runtime's limit). The mic dictates: ✓ puts the words in, ↑ sends them. Below: the model and Ask Me / Allow All, one click each.
* Focus shows as a soft ring on the whole box, never a line inside it.
*/
interface Pending {
@@ -60,6 +61,25 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
const stopping = useConversation((s) => s.stopping);
const convStore = useConversationStore();
const connected = useRuntimeState((s) => s.connected);
+ const textRef = useRef(text);
+ textRef.current = text;
+ const dictation = useDictation((spoken, mode) => {
+ const next = joinText(textRef.current, spoken);
+ if (mode === "send") { void submit(next); return; }
+ setText(next);
+ requestAnimationFrame(() => { const el = ref.current; if (el) { el.focus(); el.setSelectionRange(el.value.length, el.value.length); } });
+ });
+ const recording = dictation.phase === "recording";
+ // Esc throws the take away, Enter sends it, while recording.
+ useEffect(() => {
+ if (!recording) return;
+ const onKey = (e: KeyboardEvent) => {
+ if (e.key === "Escape") { e.preventDefault(); dictation.finish("cancel"); }
+ else if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); dictation.finish(canSendRef.current ? "send" : "insert"); }
+ };
+ window.addEventListener("keydown", onKey, true);
+ return () => window.removeEventListener("keydown", onKey, true);
+ }, [recording]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (draft == null) return;
@@ -123,8 +143,8 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
});
}
- async function submit() {
- const content = text.trim();
+ async function submit(override?: string) {
+ const content = (override ?? text).trim();
if ((!content && files.length === 0) || sending) return;
setSending(true);
setError(null);
@@ -149,11 +169,14 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
void stopTurn(convStore).catch((err) => setError(err instanceof Error ? `Couldn't stop: ${err.message}` : "Couldn't stop"));
}
const canSend = connected && !blockedReason && (text.trim().length > 0 || files.length > 0);
+ const canSendRef = useRef(false);
+ canSendRef.current = connected && !blockedReason;
return (
<div className="shrink-0 px-8 pb-6 pt-2">
<div className="mx-auto w-full max-w-[780px]">
{error && <div className="mb-2 px-1 text-sm text-red">{error}</div>}
+ <DictationNotice d={dictation} className="mb-2" />
<div
onDragOver={(e) => { if (e.dataTransfer.types.includes("Files")) { e.preventDefault(); setDragging(true); } }}
onDragLeave={() => setDragging(false)}
@@ -180,6 +203,9 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
))}
</div>
)}
+ {recording ? (
+ <div className="px-4 pb-1 pt-3"><RecordingBar d={dictation} canSend={connected && !blockedReason} /></div>
+ ) : (
<div className="flex">
{mono && <span aria-hidden="true" className="pointer-events-none select-none pl-5 pt-4 font-mono text-md leading-[26px] text-accent">&gt;</span>}
<textarea
@@ -200,6 +226,7 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
aria-label="Message"
/>
</div>
+ )}
<div className="flex flex-wrap items-center gap-1 px-3 pb-3 pt-1.5">
<Tooltip label="Attach images or PDFs" side="top">
<Button variant="ghost" size="md" icon onClick={() => picker.current?.click()} disabled={!connected || files.length >= MAX_FILES} aria-label="Attach">
@@ -223,7 +250,8 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
) : text.length > 0 ? (
<span className="mr-2 hidden text-2xs text-ink4 sm:inline">⇧↵ new line</span>
) : null}
- {showStop ? (
+ {!recording && <MicButton d={dictation} disabled={!connected} />}
+ {recording ? null : showStop ? (
<Tooltip label={stopping ? "Stopping…" : "Stop"} shortcut="esc" side="top">
<Button variant="primary" size="md" icon onClick={stop} disabled={stopping || !connected} aria-label="Stop" className="!rounded-full">
<Square size={13} className="fill-current" strokeWidth={0} />