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 call mode with living circles, minimize to a pill

Salman Qureshi68f783fea8f5
diff --git a/apps/desktop/src/app/voice.ts b/apps/desktop/src/app/voice.ts
index d0df7e5b..653f1c36 100644
--- a/apps/desktop/src/app/voice.ts
+++ b/apps/desktop/src/app/voice.ts
@@ -10,11 +10,12 @@ import { http } from "~/api/client";
import { openStream } from "~/api/stream";
import { isTauri } from "~/shell/tauri";
-export type VoiceAction = "mute" | "unmute" | "interrupt" | "stop";
+export type VoiceAction = "start" | "mute" | "unmute" | "interrupt" | "stop";
export interface VoiceTurn {
id: number;
- role: "owner" | "mercury" | "activity" | "approval" | "system";
+ /** result: the full answer behind what Mercury said out loud. */
+ role: "owner" | "mercury" | "result" | "activity" | "approval" | "system";
text: string;
at: number;
}
@@ -33,6 +34,8 @@ export interface VoiceState {
thinking: boolean;
activity: string | null;
outcome: string | null;
+ /** The chat thread this call is being saved to, live. */
+ threadId?: string | null;
turns: VoiceTurn[];
}
@@ -58,7 +61,7 @@ export const PHASE_LABEL: Record<VoicePhase, string> = {
const EMPTY: VoiceState = {
available: false, plugin: null, active: false, callId: null, startedAt: null, endedAt: null,
- listening: false, speaking: false, working: false, muted: false, thinking: false, activity: null, outcome: null, turns: [],
+ listening: false, speaking: false, working: false, muted: false, thinking: false, activity: null, outcome: null, threadId: null, turns: [],
};
export const useVoice = create<VoiceState & { supported: boolean }>(() => ({ ...EMPTY, supported: true }));
@@ -67,6 +70,39 @@ export async function voiceControl(action: VoiceAction): Promise<void> {
await http.post("/api/voice/control", { action });
}
+/** How loud you (mic) and Mercury (out) are right now, 0-1. Updated ~12×/s; read in animation frames, not renders. */
+export const useVoiceLevels = create<{ mic: number; out: number; at: number }>(() => ({ mic: 0, out: 0, at: 0 }));
+
+/**
+ * The call screen: full window, or a small floating pill while you do
+ * other things. `starting` covers the moment between pressing call and
+ * Optimus answering; `error` when it couldn't start.
+ */
+export const useCall = create<{ view: "full" | "mini"; starting: boolean; error: string | null }>(() => ({ view: "mini", starting: false, error: null }));
+
+/** Start a call from the app: opens the call screen and asks Optimus to start listening. */
+export async function startCall(): Promise<void> {
+ if (useVoice.getState().active) { useCall.setState({ view: "full" }); return; }
+ useCall.setState({ view: "full", starting: true, error: null });
+ try {
+ await voiceControl("start");
+ } catch (e) {
+ useCall.setState({ starting: false, error: e instanceof Error ? e.message : String(e) });
+ return;
+ }
+ // Optimus answers in a second or two; if nothing comes, say so instead of waiting forever.
+ setTimeout(() => {
+ const c = useCall.getState();
+ if (c.starting && !useVoice.getState().active) {
+ useCall.setState({ starting: false, error: "Optimus didn't start listening. Check Settings → Voice (engine and key) and that the microphone is allowed for Optimus." });
+ }
+ }, 12_000);
+}
+
+/** Called on every new line of a call (the chat view refreshes the call's thread if it's open). */
+let onCallTurn: ((threadId: string | null) => void) | null = null;
+export function setOnCallTurn(fn: ((threadId: string | null) => void) | null): void { onCallTurn = fn; }
+
/** Main window: stream the feed, mirror it to the capsule, show/hide the capsule. */
export function useVoiceFeed(connectionId: string): void {
useEffect(() => {
@@ -80,9 +116,19 @@ export function useVoiceFeed(connectionId: string): void {
const data = JSON.parse(raw);
if (event === "state") {
const { turns, ...rest } = data as VoiceState;
+ const was = useVoice.getState();
useVoice.setState((s) => ({ ...s, ...rest, turns: Array.isArray(turns) ? turns : rest.active && !s.active ? [] : s.turns, supported: true }));
+ if (rest.active && !was.active) useCall.setState((c) => ({ starting: false, error: null, view: c.starting ? "full" : c.view }));
+ if (!rest.active && was.active) {
+ useVoiceLevels.setState({ mic: 0, out: 0, at: Date.now() });
+ const failed = typeof rest.outcome === "string" && rest.outcome.startsWith("failed");
+ useCall.setState({ starting: false, error: failed ? `The call couldn't continue: ${rest.outcome!.replace(/^failed:?\s*/, "")}` : null });
+ }
} else if (event === "turn") {
useVoice.setState((s) => ({ turns: [...s.turns.filter((t) => t.id !== (data as VoiceTurn).id), data as VoiceTurn].slice(-200) }));
+ onCallTurn?.(useVoice.getState().threadId ?? null);
+ } else if (event === "level") {
+ useVoiceLevels.setState(data as { mic: number; out: number; at: number });
}
} catch { /* ignore a bad frame */ }
},
diff --git a/apps/desktop/src/components/VoiceOrb.tsx b/apps/desktop/src/components/VoiceOrb.tsx
new file mode 100644
index 00000000..12cbe136
--- /dev/null
+++ b/apps/desktop/src/components/VoiceOrb.tsx
@@ -0,0 +1,119 @@
+import { useEffect, useRef } from "react";
+import { useVoiceLevels, type VoicePhase } from "~/app/voice";
+
+/**
+ * The call's living circles. Three soft, overlapping discs drift around a
+ * centre and swell with the voice: yours while you talk (greens), Mercury's
+ * while it answers (blues and violets). Thinking and working breathe slowly
+ * with a turning ring; muted goes grey and still. Levels are read straight
+ * from the store each frame, so the rest of the app never re-renders for it.
+ */
+
+type OrbPhase = VoicePhase | "starting";
+
+const PALETTES: Record<OrbPhase, [string, string, string]> = {
+ listening: ["#34E1A1", "#2BB5C9", "#7FD8E8"],
+ speaking: ["#5B8DEF", "#9B7BD8", "#2BB5C9"],
+ thinking: ["#9B7BD8", "#5B8DEF", "#E0739B"],
+ working: ["#D4A72C", "#E8894A", "#5B8DEF"],
+ muted: ["#8A97A3", "#6B7680", "#A9B3BB"],
+ starting: ["#7FD8E8", "#5B8DEF", "#34E1A1"],
+ off: ["#8A97A3", "#6B7680", "#A9B3BB"],
+};
+
+function rgba(hex: string, a: number): string {
+ const n = parseInt(hex.slice(1), 16);
+ return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${a})`;
+}
+
+export function VoiceOrb({ size, phase, className }: { size: number; phase: OrbPhase; className?: string }) {
+ const ref = useRef<HTMLCanvasElement>(null);
+ const phaseRef = useRef(phase);
+ phaseRef.current = phase;
+
+ useEffect(() => {
+ const canvas = ref.current;
+ if (!canvas) return;
+ const ctx = canvas.getContext("2d");
+ if (!ctx) return;
+ const dpr = Math.min(2, window.devicePixelRatio || 1);
+ canvas.width = size * dpr;
+ canvas.height = size * dpr;
+ ctx.scale(dpr, dpr);
+ const still = window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ?? false;
+ let level = 0;
+ let colors = PALETTES[phaseRef.current].map((c) => c);
+ let raf = 0;
+ const start = performance.now();
+
+ const frame = (now: number) => {
+ const t = (now - start) / 1000;
+ const p = phaseRef.current;
+ const lv = useVoiceLevels.getState();
+ const fresh = Date.now() - lv.at < 450;
+ const target = !fresh ? 0 : p === "speaking" ? lv.out : p === "listening" ? lv.mic : p === "muted" || p === "off" ? 0 : Math.max(lv.mic, lv.out) * 0.4;
+ // Rise fast, fall gently: reads like a voice, not a meter.
+ level += (target - level) * (target > level ? 0.35 : 0.08);
+ colors = PALETTES[p];
+
+ const c = size / 2;
+ const r = size * 0.3;
+ ctx.clearRect(0, 0, size, size);
+
+ // Soft halo.
+ const haloR = r * (1.35 + level * 0.45 + (p === "thinking" || p === "working" || p === "starting" ? Math.sin(t * 1.6) * 0.05 : 0));
+ const halo = ctx.createRadialGradient(c, c, r * 0.4, c, c, haloR);
+ halo.addColorStop(0, rgba(colors[0], 0.18));
+ halo.addColorStop(1, rgba(colors[0], 0));
+ ctx.fillStyle = halo;
+ ctx.beginPath();
+ ctx.arc(c, c, haloR, 0, Math.PI * 2);
+ ctx.fill();
+
+ ctx.globalCompositeOperation = "lighter";
+ const calm = p === "muted" || p === "off";
+ for (let i = 0; i < 3; i++) {
+ const speed = calm || still ? 0 : 0.35 + i * 0.18 + level * 0.9;
+ const angle = t * speed + i * 2.09;
+ const drift = r * (0.1 + level * 0.18);
+ const x = c + Math.cos(angle) * drift;
+ const y = c + Math.sin(angle * 1.1) * drift;
+ const breathe = still ? 0 : Math.sin(t * (1.1 + i * 0.3) + i) * 0.05;
+ const rr = r * (0.78 + breathe + level * (0.42 - i * 0.08));
+ const g = ctx.createRadialGradient(x - rr * 0.3, y - rr * 0.3, rr * 0.1, x, y, rr);
+ g.addColorStop(0, rgba(colors[i], calm ? 0.5 : 0.85));
+ g.addColorStop(0.7, rgba(colors[i], calm ? 0.25 : 0.45));
+ g.addColorStop(1, rgba(colors[i], 0));
+ ctx.fillStyle = g;
+ ctx.beginPath();
+ ctx.arc(x, y, rr, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ ctx.globalCompositeOperation = "source-over";
+
+ // Thinking / working / starting: a slow turning ring of dashes.
+ if ((p === "thinking" || p === "working" || p === "starting") && !still) {
+ ctx.save();
+ ctx.translate(c, c);
+ ctx.rotate(t * 0.9);
+ ctx.strokeStyle = rgba(colors[1], 0.55);
+ ctx.lineWidth = Math.max(1.5, size * 0.008);
+ ctx.lineCap = "round";
+ const ringR = r * 1.18;
+ for (let k = 0; k < 3; k++) {
+ ctx.beginPath();
+ ctx.arc(0, 0, ringR, k * (Math.PI * 2 / 3), k * (Math.PI * 2 / 3) + 0.9);
+ ctx.stroke();
+ }
+ ctx.restore();
+ }
+
+ if (!document.hidden) raf = requestAnimationFrame(frame);
+ else raf = window.setTimeout(() => { raf = requestAnimationFrame(frame); }, 250) as unknown as number;
+ };
+ raf = requestAnimationFrame(frame);
+ return () => { cancelAnimationFrame(raf); clearTimeout(raf); };
+ }, [size]);
+
+ return <canvas ref={ref} style={{ width: size, height: size }} className={className} aria-hidden="true" />;
+}
diff --git a/apps/desktop/src/layout/Workspace.tsx b/apps/desktop/src/layout/Workspace.tsx
index 0860bc99..31cb37b2 100644
--- a/apps/desktop/src/layout/Workspace.tsx
+++ b/apps/desktop/src/layout/Workspace.tsx
@@ -19,6 +19,7 @@ import { SettingsView } from "~/views/settings/SettingsView";
import { BrainView } from "~/views/brain/BrainView";
import { ErrorBoundary } from "~/components/ErrorBoundary";
import { CloudBanner } from "~/views/settings/Cloud";
+import { CallLayer } from "~/views/call/Call";
registerBuiltinStatusItems();
@@ -59,6 +60,7 @@ export function Workspace({ connection, health, onSwitchConnection }: { connecti
</main>
</div>
<StatusBar />
+ <CallLayer />
</div>
);
}
diff --git a/apps/desktop/src/views/call/Call.tsx b/apps/desktop/src/views/call/Call.tsx
new file mode 100644
index 00000000..5f115d76
--- /dev/null
+++ b/apps/desktop/src/views/call/Call.tsx
@@ -0,0 +1,200 @@
+import { ChevronDown, Maximize2, MessageSquareText, Mic, MicOff, Pause, PhoneOff, ScrollText, X } from "lucide-react";
+import { useEffect, useRef, useState } from "react";
+import { PHASE_LABEL, phaseOf, useCall, useVoice, voiceControl, type VoiceTurn } from "~/app/voice";
+import { useUi } from "~/app/store";
+import { openThread } from "~/app/events";
+import { VoiceOrb } from "~/components/VoiceOrb";
+import { Button } from "~/components/ui/Button";
+import { Tooltip } from "~/components/ui/Tooltip";
+import { cx } from "~/lib/cx";
+
+/**
+ * Calling mode. Full window: the living circles, what's being said as
+ * captions, and three controls (mute, pause, end). Minimize and it becomes
+ * a small pill in the corner while you use the app; the call keeps going
+ * and its chat thread fills in live. The notch capsule still shows it when
+ * the window is away.
+ */
+
+export function CallLayer() {
+ const v = useVoice();
+ const call = useCall();
+ const show = v.active || call.starting || !!call.error;
+ if (!show) return null;
+ if (call.view === "full") return <CallScreen />;
+ return v.active ? <CallPill /> : null;
+}
+
+function useClock(startedAt: number | null, active: boolean): string {
+ const [, tick] = useState(0);
+ useEffect(() => {
+ if (!active) return;
+ const t = setInterval(() => tick((n) => n + 1), 1000);
+ return () => clearInterval(t);
+ }, [active]);
+ const secs = startedAt ? Math.max(0, Math.floor((Date.now() - startedAt) / 1000)) : 0;
+ return `${Math.floor(secs / 60)}:${String(secs % 60).padStart(2, "0")}`;
+}
+
+function openCallThread(threadId: string | null | undefined) {
+ if (!threadId) return;
+ useUi.getState().setView("chat");
+ useUi.getState().setVoiceOpen(false);
+ void openThread("chat", threadId);
+}
+
+function CallScreen() {
+ const v = useVoice();
+ const call = useCall();
+ const phase = call.starting && !v.active ? "starting" : phaseOf(v);
+ const clock = useClock(v.startedAt, v.active);
+ const [transcript, setTranscript] = useState(false);
+ const minimize = () => useCall.setState({ view: "mini" });
+
+ useEffect(() => {
+ const onKey = (e: KeyboardEvent) => {
+ const t = e.target as HTMLElement | null;
+ if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.isContentEditable)) return;
+ if (e.key === "Escape") { e.preventDefault(); if (call.error && !v.active) useCall.setState({ error: null }); else minimize(); }
+ else if ((e.key === "m" || e.key === "M") && v.active && !e.metaKey && !e.ctrlKey) { e.preventDefault(); void voiceControl(v.muted ? "unmute" : "mute").catch(() => {}); }
+ };
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, [v.active, v.muted, call.error]);
+
+ const said = v.turns.filter((t) => t.role === "owner" || t.role === "mercury");
+ const lastOwner = [...said].reverse().find((t) => t.role === "owner");
+ const lastMercury = [...said].reverse().find((t) => t.role === "mercury");
+ const label = phase === "starting" ? "Starting…" : v.activity && (phase === "working" || phase === "thinking") ? v.activity : PHASE_LABEL[phase as keyof typeof PHASE_LABEL] ?? "";
+
+ return (
+ <div className="fixed inset-0 z-[70] flex bg-bg/95 backdrop-blur-xl animate-fade-in" role="dialog" aria-label="Voice call">
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex h-[52px] shrink-0 items-center gap-3 px-5" data-tauri-drag-region>
+ <span className="text-sm font-medium text-ink">Voice call</span>
+ {v.active && <span className="font-mono text-sm tabular-nums text-ink3">{clock}</span>}
+ <span className="flex-1" data-tauri-drag-region />
+ {v.threadId && (
+ <Tooltip label="Open this call's chat" side="bottom">
+ <Button size="sm" variant="ghost" onClick={() => { minimize(); openCallThread(v.threadId); }}><MessageSquareText size={14} /> Chat</Button>
+ </Tooltip>
+ )}
+ <Tooltip label="Transcript" side="bottom">
+ <Button size="sm" variant={transcript ? "outline" : "ghost"} icon onClick={() => setTranscript((x) => !x)} aria-label="Transcript" aria-pressed={transcript}><ScrollText size={15} /></Button>
+ </Tooltip>
+ <Tooltip label="Minimize (keeps the call going)" shortcut="esc" side="bottom">
+ <Button size="sm" variant="ghost" icon onClick={minimize} aria-label="Minimize call"><ChevronDown size={17} /></Button>
+ </Tooltip>
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col items-center justify-center gap-6 px-8">
+ <VoiceOrb size={280} phase={phase} />
+ <div className="flex min-h-[24px] items-center gap-2 text-base text-ink2" aria-live="polite">
+ {label}
+ </div>
+ {call.error && !v.active ? (
+ <div className="flex max-w-[480px] flex-col items-center gap-3 text-center">
+ <p className="text-sm text-red">{call.error}</p>
+ <div className="flex gap-2">
+ <Button size="sm" variant="outline" onClick={() => { useCall.setState({ error: null }); useUi.getState().openSettings("voice"); }}>Voice settings</Button>
+ <Button size="sm" variant="ghost" onClick={() => useCall.setState({ error: null })}>Close</Button>
+ </div>
+ </div>
+ ) : (
+ <div className="flex w-full max-w-[640px] flex-col items-center gap-2 text-center">
+ {lastOwner && <p className="line-clamp-2 text-sm text-ink3" key={`o${lastOwner.id}`}>{lastOwner.text}</p>}
+ {lastMercury && <p className="line-clamp-3 text-lg leading-relaxed text-ink" key={`m${lastMercury.id}`}>{lastMercury.text}</p>}
+ {!lastOwner && !lastMercury && v.active && <p className="text-sm text-ink4">Go ahead, I'm listening.</p>}
+ </div>
+ )}
+ </div>
+
+ <div className="flex shrink-0 items-center justify-center gap-4 pb-10 pt-4">
+ {v.active && (
+ <>
+ <Tooltip label={v.muted ? "Unmute" : "Mute"} shortcut="M" side="top">
+ <button onClick={() => void voiceControl(v.muted ? "unmute" : "mute").catch(() => {})} aria-label={v.muted ? "Unmute" : "Mute"} aria-pressed={v.muted}
+ className={cx("flex h-14 w-14 items-center justify-center rounded-full border transition-colors", v.muted ? "border-ink bg-ink text-bg" : "border-line bg-surface text-ink hover:bg-ink/[0.06]")}>
+ {v.muted ? <MicOff size={20} /> : <Mic size={20} />}
+ </button>
+ </Tooltip>
+ {(v.speaking || v.working || v.thinking) && (
+ <Tooltip label="Stop what it's saying or doing" side="top">
+ <button onClick={() => void voiceControl("interrupt").catch(() => {})} aria-label="Pause"
+ className="flex h-14 w-14 items-center justify-center rounded-full border border-line bg-surface text-ink hover:bg-ink/[0.06]"><Pause size={20} /></button>
+ </Tooltip>
+ )}
+ </>
+ )}
+ <Tooltip label={v.active ? "End call" : "Close"} side="top">
+ <button onClick={() => { if (v.active) void voiceControl("stop").catch(() => {}); useCall.setState({ starting: false, error: null, view: "mini" }); }}
+ aria-label={v.active ? "End call" : "Close"} className="flex h-14 w-14 items-center justify-center rounded-full bg-red text-white hover:bg-red/90">
+ {v.active || call.starting ? <PhoneOff size={20} /> : <X size={20} />}
+ </button>
+ </Tooltip>
+ </div>
+ </div>
+
+ {transcript && <TranscriptPanel turns={v.turns} onClose={() => setTranscript(false)} />}
+ </div>
+ );
+}
+
+function TranscriptPanel({ turns, onClose }: { turns: VoiceTurn[]; onClose: () => void }) {
+ const ref = useRef<HTMLDivElement>(null);
+ useEffect(() => { const el = ref.current; if (el) el.scrollTop = el.scrollHeight; }, [turns.length]);
+ return (
+ <aside className="flex w-[360px] shrink-0 flex-col border-l border-line bg-soft/80">
+ <div className="flex h-[52px] items-center justify-between px-4"><span className="text-sm font-medium text-ink">Transcript</span>
+ <button onClick={onClose} className="text-ink4 hover:text-ink" aria-label="Close transcript"><X size={15} /></button></div>
+ <div ref={ref} className="flex min-h-0 flex-1 flex-col gap-3 overflow-y-auto px-4 pb-6" data-selectable>
+ {turns.length === 0 && <p className="text-sm text-ink4">Nothing said yet.</p>}
+ {turns.map((t) => (
+ <div key={t.id} className={cx("text-sm leading-relaxed",
+ t.role === "owner" && "self-end rounded-2xl rounded-br-md bg-ink/[0.07] px-3 py-2 text-ink",
+ t.role === "mercury" && "text-ink",
+ t.role === "result" && "rounded-lg border border-line bg-surface px-3 py-2 text-xs text-ink2",
+ (t.role === "activity" || t.role === "system") && "text-xs text-ink4",
+ t.role === "approval" && "rounded-lg border border-amber/40 bg-amber/[0.06] px-3 py-2 text-xs text-ink2")}>
+ {t.role === "result" && <span className="mb-1 block text-2xs uppercase tracking-wider text-ink4">Full answer</span>}
+ {t.text}
+ </div>
+ ))}
+ </div>
+ </aside>
+ );
+}
+
+function CallPill() {
+ const v = useVoice();
+ const phase = phaseOf(v);
+ const clock = useClock(v.startedAt, v.active);
+ const expand = () => useCall.setState({ view: "full" });
+ return (
+ <div className="fixed bottom-14 right-5 z-[65] flex items-center gap-2 rounded-full border border-line bg-surface/95 py-1.5 pl-1.5 pr-2 shadow-xl backdrop-blur animate-fade-in" role="region" aria-label="Voice call">
+ <button onClick={expand} className="flex items-center gap-2 rounded-full pr-1" aria-label="Open the call">
+ <VoiceOrb size={36} phase={phase} />
+ <span className="flex flex-col text-left leading-tight">
+ <span className="max-w-[160px] truncate text-xs font-medium text-ink">{v.activity && (phase === "working" || phase === "thinking") ? v.activity : PHASE_LABEL[phase]}</span>
+ <span className="font-mono text-2xs tabular-nums text-ink3">{clock}</span>
+ </span>
+ </button>
+ {v.threadId && (
+ <Tooltip label="Open this call's chat" side="top">
+ <Button size="sm" variant="ghost" icon onClick={() => openCallThread(v.threadId)} aria-label="Open the call's chat"><MessageSquareText size={14} /></Button>
+ </Tooltip>
+ )}
+ <Tooltip label={v.muted ? "Unmute" : "Mute"} side="top">
+ <Button size="sm" variant={v.muted ? "secondary" : "ghost"} icon onClick={() => void voiceControl(v.muted ? "unmute" : "mute").catch(() => {})} aria-label={v.muted ? "Unmute" : "Mute"}>
+ {v.muted ? <MicOff size={14} /> : <Mic size={14} />}
+ </Button>
+ </Tooltip>
+ <Tooltip label="Full screen" side="top">
+ <Button size="sm" variant="ghost" icon onClick={expand} aria-label="Full screen"><Maximize2 size={13} /></Button>
+ </Tooltip>
+ <Tooltip label="End call" side="top">
+ <button onClick={() => void voiceControl("stop").catch(() => {})} aria-label="End call" className="flex h-7 w-7 items-center justify-center rounded-full bg-red text-white hover:bg-red/90"><PhoneOff size={13} /></button>
+ </Tooltip>
+ </div>
+ );
+}
diff --git a/apps/desktop/src/views/chat/ChatView.tsx b/apps/desktop/src/views/chat/ChatView.tsx
index e1413f3f..badf0714 100644
--- a/apps/desktop/src/views/chat/ChatView.tsx
+++ b/apps/desktop/src/views/chat/ChatView.tsx
@@ -2,7 +2,7 @@ import { PanelLeft } from "lucide-react";
import { useEffect } from "react";
import { useChat, useUi } from "~/app/store";
import { conversations, ConversationContext, useCodeSessions } from "~/app/conversation";
-import { openThread } from "~/app/events";
+import { refreshThreads, openThread } from "~/app/events";
import { Button } from "~/components/ui/Button";
import { Tooltip } from "~/components/ui/Tooltip";
import { Mark } from "~/components/Logo";
@@ -10,8 +10,9 @@ import { ThreadList } from "./ThreadList";
import { Conversation } from "./Conversation";
import { VoiceConversation } from "./VoiceConversation";
import { OptimusFace } from "~/components/OptimusFace";
-import { useVoice, phaseOf, PHASE_LABEL } from "~/app/voice";
+import { useVoice, phaseOf, PHASE_LABEL, setOnCallTurn, useCall } from "~/app/voice";
import { cx } from "~/lib/cx";
+import * as api from "~/api/mercury";
/**
* Chat: sessions on the left (with New chat), one conversation. Its own
@@ -32,11 +33,21 @@ export function ChatView() {
const title = threads.find((t) => t.id === activeId)?.title || (activeId ? "Untitled" : "New chat");
const codeSet = new Set(codeIds.map((c) => c.id));
- // A voice session starting takes over: Chat opens on the live session.
- const setView = useUi((s) => s.setView);
+ // A call is saved as a chat thread, live: show it in the list, and refresh it while it's open.
+ useEffect(() => { void refreshThreads(); }, [voice.active, voice.threadId]);
useEffect(() => {
- if (voice.active) { setVoiceOpen(true); setView("chat"); }
- }, [voice.active, voice.callId, setVoiceOpen, setView]);
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ setOnCallTurn((threadId) => {
+ if (!threadId || conversations.chat.getState().activeId !== threadId) return;
+ if (timer) clearTimeout(timer);
+ timer = setTimeout(() => {
+ void api.chat.thread(threadId).then((t) => {
+ if (conversations.chat.getState().activeId === threadId) conversations.chat.getState().setMessages(t.messages ?? []);
+ }).catch(() => {});
+ }, 250);
+ });
+ return () => { setOnCallTurn(null); if (timer) clearTimeout(timer); };
+ }, []);
useEffect(() => {
const onKey = (e: KeyboardEvent) => {
@@ -60,7 +71,12 @@ export function ChatView() {
newLabel="New chat"
searchLabel="Search chats"
pinned={(voice.active || voice.turns.length > 0) && (
- <button onClick={() => setVoiceOpen(true)}
+ <button onClick={() => {
+ // A live call opens the call screen; a finished one opens its chat.
+ if (voice.active) { useCall.setState({ view: "full" }); return; }
+ if (voice.threadId) { setVoiceOpen(false); void openThread("chat", voice.threadId); return; }
+ setVoiceOpen(true);
+ }}
className={cx("mb-3 flex w-full items-center gap-3 rounded-lg border px-3 py-2.5 text-left", voiceOpen ? "border-line-strong bg-ink/[0.07]" : "border-line bg-surface hover:border-line-strong")}>
<OptimusFace size={30} phase={voicePhase} />
<span className="min-w-0 flex-1">
diff --git a/apps/desktop/src/views/chat/Composer.tsx b/apps/desktop/src/views/chat/Composer.tsx
index fcb55f3a..e2c4c56a 100644
--- a/apps/desktop/src/views/chat/Composer.tsx
+++ b/apps/desktop/src/views/chat/Composer.tsx
@@ -1,9 +1,10 @@
-import { ArrowUp, ChevronDown, Paperclip, Shield, ShieldCheck, Square, X } from "lucide-react";
+import { ArrowUp, AudioLines, ChevronDown, Paperclip, Shield, ShieldCheck, Square, X } from "lucide-react";
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { cx } from "~/lib/cx";
import * as api from "~/api/mercury";
import type { ChatSettings, ModelsResponse } from "~/api/types";
import { useRuntimeState } from "~/app/store";
+import { startCall, useVoice } from "~/app/voice";
import { sendMessage, stopTurn, type CodeTurn } from "~/app/events";
import { useConversation, useConversationStore, type Surface } from "~/app/conversation";
import { Button } from "~/components/ui/Button";
@@ -70,6 +71,7 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
requestAnimationFrame(() => { const el = ref.current; if (el) { el.focus(); el.setSelectionRange(el.value.length, el.value.length); } });
});
const recording = dictation.phase === "recording";
+ const voiceAvailable = useVoice((s) => s.available && s.supported && !s.active);
// Esc throws the take away, Enter sends it, while recording.
useEffect(() => {
if (!recording) return;
@@ -251,7 +253,14 @@ export function Composer({ surface, placeholder, code, extra, blockedReason, mon
<span className="mr-2 hidden text-2xs text-ink4 sm:inline">⇧↵ new line</span>
) : null}
{!recording && <MicButton d={dictation} disabled={!connected} />}
- {recording ? null : showStop ? (
+ {!recording && surface === "chat" && voiceAvailable && !text.trim() && files.length === 0 && !busy && (
+ <Tooltip label="Talk to Mercury (voice call)" side="top">
+ <Button variant="secondary" size="md" icon onClick={() => void startCall()} disabled={!connected} aria-label="Start a voice call" className="!rounded-full">
+ <AudioLines size={17} />
+ </Button>
+ </Tooltip>
+ )}
+ {recording || (surface === "chat" && voiceAvailable && !text.trim() && files.length === 0 && !busy) ? 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} />