Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(live-voice): stage call interaction UI

vastsa7770b9a75d74
diff --git a/apps/desktop/src/components/icons.tsx b/apps/desktop/src/components/icons.tsx
index f7bb43eec..421d000e3 100644
--- a/apps/desktop/src/components/icons.tsx
+++ b/apps/desktop/src/components/icons.tsx
@@ -9,6 +9,7 @@ import {
ArrowUpDown,
ArrowUpRight,
AtSign,
+ AudioLines,
Bell,
BookOpen,
Bot,
@@ -51,6 +52,7 @@ import {
ListChecks,
LogOut,
Mic,
+ MicOff,
Minus,
MessageSquare,
MessageSquarePlus,
@@ -65,6 +67,7 @@ import {
Maximize2,
Minimize2,
PawPrint,
+ PhoneOff,
PencilLine,
Pin,
Play,
@@ -93,6 +96,7 @@ import {
UserRound,
Undo2,
Video,
+ Volume2,
Webhook,
Workflow,
Wrench,
@@ -214,6 +218,10 @@ export const IconVideo = icon(Video);
export const IconReview = icon(RefreshCw);
export const IconKeyboard = icon(Keyboard);
export const IconMic = icon(Mic);
+export const IconMicOff = icon(MicOff);
+export const IconWaveform = icon(AudioLines);
+export const IconPhoneOff = icon(PhoneOff);
+export const IconVolume = icon(Volume2);
export const IconPlug = icon(Plug);
export const IconSlash = icon(Slash);
export const IconUser = icon(UserRound);
diff --git a/apps/desktop/src/features/app/AppShell.tsx b/apps/desktop/src/features/app/AppShell.tsx
index a211e8f63..7dc307afe 100644
--- a/apps/desktop/src/features/app/AppShell.tsx
+++ b/apps/desktop/src/features/app/AppShell.tsx
@@ -20,6 +20,7 @@ import { WorkPanel } from "../../components/workpanel/WorkPanel";
import { useCopyTex } from "../../hooks/use-copy-tex";
import { api } from "../../lib/api";
import { PortalVisibilityProvider } from "../../lib/portal-visibility";
+import { LiveVoiceStatusHost } from "../voice/live/LiveVoiceStatusHost";
import { CollapsedTitlebarActions, RoutePending } from "./chrome";
import { useAppShellRuntime } from "./useAppShellRuntime";
@@ -295,6 +296,7 @@ export function AppShell() {
) : null}
<SearchDialog open={searchOpen} onClose={() => setSearchOpen(false)} />
<ToastHost />
+ <LiveVoiceStatusHost />
<PluginRendererHost />
<ExtensionPromptHost />
{page === "settings" ? <UpdateBanner /> : null}
diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
index 0b3207965..3df8e0c8f 100644
--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
@@ -121,7 +121,7 @@ export function ComposerToolbar({
<IconPlus size={15} aria-hidden="true" />
</TooltipButton>
</div>
- <LiveVoiceControls t={t} workSessionId={workSessionId} workSessionLabel={workSessionLabel} />
+ <LiveVoiceControls t={t} workSessionId={workSessionId} />
<TooltipButton
type="button"
className="icon-btn mode-chip composer-mode-chip"
diff --git a/apps/desktop/src/features/voice/live/LiveVoiceCallBar.tsx b/apps/desktop/src/features/voice/live/LiveVoiceCallBar.tsx
new file mode 100644
index 000000000..04b4faf45
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/LiveVoiceCallBar.tsx
@@ -0,0 +1,106 @@
+import type { RefObject } from "react";
+import type { TFunction } from "i18next";
+import { IconClose, IconInfo, IconMic, IconMicOff, IconPhoneOff, IconSettings, IconVolume, IconWaveform } from "../../../components/icons";
+import { TooltipButton } from "../../../components/ui";
+import type { LiveVoiceSnapshot } from "./live-call-controller";
+import { liveVoiceMode, type liveVoiceIssue } from "./live-voice-presentation";
+
+type CallBarProps = {
+ t: TFunction;
+ snapshot: LiveVoiceSnapshot;
+ issue: ReturnType<typeof liveVoiceIssue>;
+ detailsOpen: boolean;
+ detailsRef: RefObject<HTMLButtonElement | null>;
+ actionPending: "mute" | "playback" | null;
+ onCancel: () => void;
+ onMute: () => void;
+ onEnd: () => void;
+ onDetails: () => void;
+ onResume: () => void;
+ onSettings: () => void;
+ onDismiss: () => void;
+};
+
+export function LiveVoiceCallBar({
+ t, snapshot, issue, detailsOpen, detailsRef, actionPending,
+ onCancel, onMute, onEnd, onDetails, onResume, onSettings, onDismiss,
+}: CallBarProps) {
+ const mode = liveVoiceMode(snapshot);
+ const call = snapshot.call;
+ const status = mode === "stopping" ? "liveVoice.phase.closing"
+ : mode === "connecting" ? "liveVoice.phase.connecting"
+ : mode === "reconnecting" ? "liveVoice.phase.reconnecting"
+ : mode === "idle" ? "liveVoice.phase.failed"
+ : call?.muted ? "liveVoice.muted"
+ : call?.userSpeaking ? "liveVoice.userSpeaking"
+ : call?.assistantSpeaking ? "liveVoice.assistantSpeaking"
+ : "liveVoice.phase.connected";
+ const unmute = call?.muted !== false;
+ const speaking = mode === "connected" && (call?.assistantSpeaking || (call?.userSpeaking && !call.muted));
+
+ return (
+ <div className="live-voice-call-bar" data-state={mode}>
+ <div className="live-voice-call-row">
+ <div className="live-voice-call-status" role="status" aria-live="polite" aria-atomic="true">
+ {mode === "connecting" || mode === "reconnecting" || mode === "stopping"
+ ? <span className="voice-spinner" aria-hidden="true" />
+ : <IconWaveform size={17} className={speaking ? "voice-mic-active" : undefined} aria-hidden="true" />}
+ <span><strong>{t("liveVoice.title")}</strong><span className="live-voice-status-text"> · {t(status)}</span></span>
+ </div>
+ <div className="live-voice-call-actions">
+ {mode === "connecting" ? (
+ <TooltipButton type="button" className="icon-btn icon-btn-square" tooltip={t("common.cancel")} onClick={onCancel}>
+ <IconClose size={17} aria-hidden="true" />
+ </TooltipButton>
+ ) : null}
+ {mode === "connected" || mode === "reconnecting" ? (
+ <>
+ {call?.playbackBlocked ? (
+ <TooltipButton type="button" className="icon-btn icon-btn-square live-voice-resume" tooltip={t("liveVoice.resumePlayback")} disabled={actionPending === "playback"} onClick={onResume}>
+ <IconVolume size={17} aria-hidden="true" />
+ </TooltipButton>
+ ) : null}
+ {mode === "connected" ? (
+ <TooltipButton
+ type="button"
+ className={`icon-btn icon-btn-square${unmute ? " live-voice-muted" : ""}`}
+ tooltip={t(unmute ? "liveVoice.unmute" : "liveVoice.mute")}
+ aria-pressed={call?.muted ?? true}
+ disabled={actionPending === "mute"}
+ onClick={onMute}
+ >
+ {unmute ? <IconMicOff size={17} aria-hidden="true" /> : <IconMic size={17} aria-hidden="true" />}
+ </TooltipButton>
+ ) : null}
+ <TooltipButton type="button" className="icon-btn icon-btn-square live-voice-end" tooltip={t("liveVoice.end")} onClick={onEnd}>
+ <IconPhoneOff size={17} aria-hidden="true" />
+ </TooltipButton>
+ </>
+ ) : null}
+ {(mode === "connected" || mode === "reconnecting" || mode === "idle") && call ? (
+ <TooltipButton ref={detailsRef} type="button" className="icon-btn icon-btn-square" tooltip={t("liveVoice.details")} aria-haspopup="dialog" aria-expanded={detailsOpen} onClick={onDetails}>
+ <IconInfo size={17} aria-hidden="true" />
+ </TooltipButton>
+ ) : null}
+ {mode === "idle" ? (
+ <>
+ <TooltipButton type="button" className="icon-btn icon-btn-square" tooltip={t("errors.action.openSettings")} onClick={onSettings}>
+ <IconSettings size={16} aria-hidden="true" />
+ </TooltipButton>
+ {issue?.code !== "LIVE_MEDIA_RELEASE_UNCONFIRMED" ? (
+ <TooltipButton type="button" className="icon-btn icon-btn-square" tooltip={t("errors.action.dismiss")} onClick={onDismiss}>
+ <IconClose size={16} aria-hidden="true" />
+ </TooltipButton>
+ ) : null}
+ </>
+ ) : null}
+ </div>
+ </div>
+ {issue ? (
+ <p className={issue.warning ? "live-voice-feedback live-voice-hint" : "live-voice-feedback live-voice-error"} role={issue.warning ? "status" : "alert"}>
+ {t(issue.message)}
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/voice/live/LiveVoiceControls.tsx b/apps/desktop/src/features/voice/live/LiveVoiceControls.tsx
index 95c328578..051fae114 100644
--- a/apps/desktop/src/features/voice/live/LiveVoiceControls.tsx
+++ b/apps/desktop/src/features/voice/live/LiveVoiceControls.tsx
@@ -1,289 +1,64 @@
-import { useEffect, useRef, useState, useSyncExternalStore } from "react";
+import { useCallback, useContext, useEffect, useRef, useState, useSyncExternalStore } from "react";
import type { TFunction } from "i18next";
-import { Badge, Button, Checkbox, Panel, Select, TooltipButton } from "../../../components/ui";
-import { IconMic, IconSparkles } from "../../../components/icons";
-import { useAppStore } from "../../../stores/app-store";
+import { IconWaveform } from "../../../components/icons";
+import { AnchoredMenu } from "../../../components/settings/AnchoredMenu";
+import { TooltipButton } from "../../../components/ui";
+import { PortalVisibilityContext } from "../../../lib/portal-visibility";
import { getLiveCallController } from "./live-call-controller";
-import { liveVoiceApi } from "./live-voice-api";
-import { LiveWorkOperations } from "./LiveWorkOperations";
+import { hasUnconfirmedMediaRelease, liveVoiceMode } from "./live-voice-presentation";
+import { LiveVoicePreparation } from "./LiveVoicePreparation";
import "../../../styles/voice.css";
-export function LiveVoiceControls({
- t,
- workSessionId,
- workSessionLabel,
-}: {
+export function LiveVoiceControls({ t, workSessionId }: {
t: TFunction;
workSessionId?: string;
- workSessionLabel?: string;
}) {
const controller = getLiveCallController();
const snapshot = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
- const sessions = useAppStore((state) => state.sessions);
- const activeSessionId = useAppStore((state) => state.activeSessionId);
- const selectSession = useAppStore((state) => state.selectSession);
- const createSession = useAppStore((state) => state.newSession);
+ const visible = useContext(PortalVisibilityContext);
const [open, setOpen] = useState(false);
- const [selectedWorkSessionId, setSelectedWorkSessionId] = useState(workSessionId ?? "");
- const [contextEnabled, setContextEnabled] = useState(false);
- const [workActionMessage, setWorkActionMessage] = useState<string | null>(null);
- const [busyOperationId, setBusyOperationId] = useState<string | null>(null);
const triggerRef = useRef<HTMLButtonElement>(null);
- const panelRef = useRef<HTMLDivElement>(null);
- const call = snapshot.call;
- const isActive = Boolean(call && !["ended", "failed", "idle"].includes(call.phase));
- const enabled = snapshot.status?.enabled === true;
- const selectable = snapshot.status?.bindings.some((item) => item.selectable) === true;
- const label = isActive ? t("liveVoice.openPanel") : t("liveVoice.start");
- const localSessions = sessions.filter((session) => session.source === undefined || session.source === "desktop").slice(0, 20);
- const selectedWorkSession = localSessions.find((session) => session.id === selectedWorkSessionId);
- const selectedWorkLabel = selectedWorkSession
- ? formatSessionLabel(selectedWorkSession.projectPath, selectedWorkSession.title, t("liveVoice.untitledWorkSession"))
- : workSessionLabel || t("liveVoice.untitledWorkSession");
- const viewingSession = sessions.find((session) => session.id === activeSessionId);
+ const mode = liveVoiceMode(snapshot);
+ const previousMode = useRef(mode);
+ const releaseUnconfirmed = hasUnconfirmedMediaRelease(snapshot);
+ const available = visible && snapshot.status?.enabled === true && mode === "idle" && !releaseUnconfirmed;
+ const close = useCallback(() => setOpen(false), []);
useEffect(() => {
- setSelectedWorkSessionId(workSessionId ?? "");
- }, [workSessionId]);
-
- useEffect(() => {
- if (!isActive) setContextEnabled(false);
- }, [isActive]);
-
- const openSelection = async (callId: string, selectionRef: string) => {
- const target = await liveVoiceApi.resolveWorkSelection({ callId, selectionRef });
- if (target.kind !== "session") throw new Error("The selected item is not a session");
- await selectSession(target.sessionId);
- };
-
- const createSessionForProject = async (callId: string, selectionRef: string) => {
- const target = await liveVoiceApi.resolveWorkSelection({ callId, selectionRef });
- if (target.kind !== "project") throw new Error("The selected item is not a project");
- await createSession({ projectPath: target.projectPath });
- const createdSessionId = useAppStore.getState().activeSessionId;
- if (!createdSessionId) throw new Error("Session creation did not select a session");
- setSelectedWorkSessionId(createdSessionId);
- setContextEnabled(false);
- };
-
- useEffect(() => {
- if (!open) return;
- const firstAction = panelRef.current?.querySelector<HTMLButtonElement>("button:not(:disabled)");
- firstAction?.focus();
- const onKeyDown = (event: KeyboardEvent) => {
- if (event.key !== "Escape") return;
- event.preventDefault();
- setOpen(false);
+ if (!available) setOpen(false);
+ if (available && previousMode.current !== "idle" && document.activeElement === document.body) {
triggerRef.current?.focus();
- };
- window.addEventListener("keydown", onKeyDown);
- return () => window.removeEventListener("keydown", onKeyDown);
- }, [open]);
+ }
+ previousMode.current = mode;
+ }, [available, mode]);
- useEffect(() => {
- if (snapshot.starting) setOpen(true);
- }, [snapshot.starting]);
-
- const closePanel = () => {
- setOpen(false);
- triggerRef.current?.focus();
- };
+ if (!available) return null;
return (
- <div className="live-voice-control">
- <TooltipButton
- type="button"
- className={`icon-btn icon-btn-square${isActive ? " voice-active" : ""}`}
- ariaLabel={label}
- aria-pressed={isActive}
- aria-expanded={open}
- aria-haspopup="dialog"
- tooltip={label}
- ref={triggerRef}
- onClick={() => {
- if (isActive || snapshot.starting) {
- setOpen((value) => !value);
- return;
- }
- setOpen(true);
- if (enabled && selectable) void controller.start().catch(() => undefined);
- }}
- >
- <IconMic size={15} aria-hidden="true" />
- </TooltipButton>
- {workSessionId ? (
+ <AnchoredMenu
+ open={open}
+ onClose={close}
+ role="dialog"
+ label={t("liveVoice.prepareCall")}
+ side="top"
+ className="live-voice-control"
+ menuClassName="live-voice-popup"
+ anchorRef={triggerRef}
+ trigger={() => (
<TooltipButton
+ ref={triggerRef}
type="button"
className="icon-btn icon-btn-square"
- ariaLabel={t("liveVoice.openWorkSetup")}
- aria-expanded={open}
+ tooltip={t("liveVoice.title")}
aria-haspopup="dialog"
- tooltip={t("liveVoice.openWorkSetup")}
- disabled={isActive || snapshot.starting}
- onClick={() => setOpen(true)}
+ aria-expanded={open}
+ onClick={() => setOpen((value) => !value)}
>
- <IconSparkles size={15} aria-hidden="true" />
+ <IconWaveform size={15} aria-hidden="true" />
</TooltipButton>
- ) : null}
- {open ? (
- <div ref={panelRef} className="live-voice-panel" role="dialog" aria-label={t("liveVoice.title")}>
- <Panel className="live-voice-panel-surface">
- <div className="live-voice-panel-heading">
- <strong>{t("liveVoice.title")}</strong>
- <Badge aria-live="polite" aria-atomic="true" tone={call?.phase === "connected" ? "success" : snapshot.errorCode ? "error" : "neutral"}>
- {t(`liveVoice.phase.${call?.phase ?? (snapshot.starting ? "preparing" : "idle")}`)}
- </Badge>
- </div>
- {snapshot.status?.selectedBindingId ? (
- <div className="live-voice-provider">
- {snapshot.status.bindings.find((item) => item.bindingId === (call?.bindingId ?? snapshot.status?.selectedBindingId))?.providerLabel ?? t("liveVoice.providerUnavailable")}
- </div>
- ) : null}
- {call?.phase === "connected" ? (
- <div className="live-voice-provider">
- {call.userSpeaking ? t("liveVoice.userSpeaking") : call.assistantSpeaking ? t("liveVoice.assistantSpeaking") : call.muted ? t("liveVoice.muted") : t("liveVoice.phase.connected")}
- </div>
- ) : null}
- {call?.workBinding ? (
- <div className="live-voice-provider" aria-live="polite">
- {t("liveVoice.boundWorkSession", { label: call.workBinding.label || t("liveVoice.untitledWorkSession") })}
- <div>{t(call.workBinding.contextEnabled ? "liveVoice.contextShared" : "liveVoice.contextNotShared")}</div>
- </div>
- ) : null}
- {call?.workBinding && activeSessionId !== call.workBinding.workSessionId ? (
- <div className="live-voice-hint">{t("liveVoice.viewingDifferentSession", { label: viewingSession ? formatSessionLabel(viewingSession.projectPath, viewingSession.title, t("liveVoice.untitledWorkSession")) : t("liveVoice.unknownSession") })}</div>
- ) : null}
- {call?.workBinding && activeSessionId !== call.workBinding.workSessionId ? (
- <Button size="sm" variant="secondary" onClick={() => void selectSession(call.workBinding!.workSessionId).catch(() => setWorkActionMessage(t("liveVoice.sessionOpenFailed")))}>
- {t("liveVoice.viewWorkSession")}
- </Button>
- ) : null}
- {call?.workBinding?.workSessionId && call.workOperations?.length ? (
- <LiveWorkOperations
- sessionId={call.workBinding.workSessionId}
- callId={call.callId}
- operations={call.workOperations}
- t={t}
- busyOperationId={busyOperationId}
- setBusyOperationId={setBusyOperationId}
- setMessage={setWorkActionMessage}
- onOpenSelection={openSelection}
- onCreateSession={createSessionForProject}
- />
- ) : null}
- {workActionMessage ? <div className="live-voice-hint" role="status">{workActionMessage}</div> : null}
- {snapshot.errorCode ? (
- <div className="live-voice-error" role="alert">
- {t(snapshot.errorCode === "LIVE_MICROPHONE_DENIED"
- ? "liveVoice.microphoneDenied"
- : snapshot.errorCode === "LIVE_MICROPHONE_BUSY"
- ? "liveVoice.microphoneBusy"
- : snapshot.errorCode === "LIVE_MICROPHONE_UNAVAILABLE"
- ? "liveVoice.microphoneUnavailable"
- : "liveVoice.errorGeneric")}
- </div>
- ) : null}
- {call?.playbackBlocked ? (
- <Button size="sm" variant="secondary" onClick={() => void controller.resumePlayback()}>
- {t("liveVoice.resumePlayback")}
- </Button>
- ) : null}
- {snapshot.transcripts.length > 0 ? (
- <div className="live-voice-transcripts" aria-live="polite" aria-relevant="additions text">
- {snapshot.transcripts.map((segment, index) => (
- <p key={`${segment.role}:${segment.id}:${index}`} data-role={segment.role}>{segment.text}</p>
- ))}
- </div>
- ) : null}
- <div className="live-voice-actions">
- {snapshot.starting ? (
- <Button size="sm" variant="secondary" onClick={() => void controller.cancelStart()}>{t("common.cancel")}</Button>
- ) : isActive ? (
- <>
- <Button size="sm" variant="secondary" aria-pressed={call?.muted ?? true} disabled={call?.phase !== "connected"} onClick={() => void controller.toggleMute()}>
- {call?.muted ? t("liveVoice.unmute") : t("liveVoice.mute")}
- </Button>
- <Button size="sm" variant="secondary" onClick={() => void controller.end()}>{t("liveVoice.end")}</Button>
- </>
- ) : (
- <>
- <Button size="sm" variant="primary" disabled={!enabled || !selectable} onClick={() => void controller.start().catch(() => undefined)}>
- {t("liveVoice.start")}
- </Button>
- {workSessionId ? (
- <Button
- size="sm"
- variant="secondary"
- disabled={!enabled || !selectable || !selectedWorkSessionId}
- onClick={() => void controller.start({ workTarget: { workSessionId: selectedWorkSessionId, contextEnabled } }).catch(() => undefined)}
- >
- {t("liveVoice.connectWorkSession", { label: selectedWorkLabel })}
- </Button>
- ) : null}
- </>
- )}
- <Button size="sm" variant="ghost" onClick={closePanel}>{t("common.close")}</Button>
- </div>
- {!enabled ? <div className="live-voice-hint">{t("liveVoice.enableInSettings")}</div> : null}
- {enabled && !selectable && !isActive ? <div className="live-voice-hint">{t("liveVoice.noProvider")}</div> : null}
- {!isActive && workSessionId ? (
- <div className="live-voice-work-setup">
- <label className="live-voice-field-label" htmlFor="live-voice-work-session">{t("liveVoice.selectWorkSession")}</label>
- <Select
- id="live-voice-work-session"
- value={selectedWorkSessionId}
- onChange={(event) => {
- setSelectedWorkSessionId(event.currentTarget.value);
- setContextEnabled(false);
- }}
- aria-label={t("liveVoice.selectWorkSession")}
- >
- {!selectedWorkSession && workSessionId ? (
- <option value={workSessionId}>{workSessionLabel || t("liveVoice.untitledWorkSession")}</option>
- ) : null}
- {localSessions.map((session) => (
- <option key={session.id} value={session.id}>
- {formatSessionLabel(session.projectPath, session.title, t("liveVoice.untitledWorkSession"))}
- </option>
- ))}
- </Select>
- <Checkbox
- checked={contextEnabled}
- onChange={(event) => setContextEnabled(event.currentTarget.checked)}
- label={t("liveVoice.shareContext")}
- aria-describedby="live-voice-context-explanation"
- />
- <div id="live-voice-context-explanation" className="live-voice-hint">
- {t("liveVoice.contextConsent")}
- </div>
- <div className="live-voice-actions">
- <Button size="sm" variant="ghost" onClick={() => void (async () => {
- setWorkActionMessage(null);
- try {
- await createSession();
- const createdSessionId = useAppStore.getState().activeSessionId;
- if (createdSessionId) {
- setSelectedWorkSessionId(createdSessionId);
- setContextEnabled(false);
- }
- } catch {
- setWorkActionMessage(t("liveVoice.sessionCreateFailed"));
- }
- })()}>
- {t("liveVoice.createWorkSession")}
- </Button>
- </div>
- </div>
- ) : null}
- </Panel>
- </div>
- ) : null}
- </div>
+ )}
+ >
+ <LiveVoicePreparation t={t} status={snapshot.status} workSessionId={workSessionId} onClose={close} />
+ </AnchoredMenu>
);
}
-
-function formatSessionLabel(projectPath: string | undefined, title: string, untitledLabel: string): string {
- const sessionLabel = title.trim() || untitledLabel;
- const projectLabel = projectPath?.split(/[\\/]/).filter(Boolean).at(-1);
- return projectLabel ? `${projectLabel} / ${sessionLabel}` : sessionLabel;
-}
diff --git a/apps/desktop/src/features/voice/live/LiveVoiceDetails.tsx b/apps/desktop/src/features/voice/live/LiveVoiceDetails.tsx
new file mode 100644
index 000000000..68650947e
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/LiveVoiceDetails.tsx
@@ -0,0 +1,117 @@
+import { useState, type RefObject } from "react";
+import type { TFunction } from "i18next";
+import type { LiveCallView, LiveStatus, LiveTranscriptSegment } from "@pi-desktop/shared";
+import { IconClose, IconExternal } from "../../../components/icons";
+import { AnchoredMenu } from "../../../components/settings/AnchoredMenu";
+import { Panel, TooltipButton } from "../../../components/ui";
+import { useAppStore } from "../../../stores/app-store";
+import { liveVoiceApi } from "./live-voice-api";
+import { formatWorkSessionLabel } from "./live-voice-presentation";
+import { LiveWorkOperations } from "./LiveWorkOperations";
+
+export function LiveVoiceDetails({ t, call, status, transcripts, open, onClose, anchorRef }: {
+ t: TFunction;
+ call: LiveCallView;
+ status: LiveStatus | null;
+ transcripts: LiveTranscriptSegment[];
+ open: boolean;
+ onClose: () => void;
+ anchorRef: RefObject<HTMLButtonElement | null>;
+}) {
+ const activeSessionId = useAppStore((state) => state.activeSessionId);
+ const sessions = useAppStore((state) => state.sessions);
+ const selectSession = useAppStore((state) => state.selectSession);
+ const createSession = useAppStore((state) => state.newSession);
+ const [message, setMessage] = useState<string | null>(null);
+ const [busyOperationId, setBusyOperationId] = useState<string | null>(null);
+ const provider = status?.bindings.find((binding) => binding.bindingId === call.bindingId);
+ const viewingSession = sessions.find((session) => session.id === activeSessionId);
+ const workBinding = call.workBinding;
+
+ const openSelection = async (callId: string, selectionRef: string) => {
+ const target = await liveVoiceApi.resolveWorkSelection({ callId, selectionRef });
+ if (target.kind !== "session") throw new Error("The selected item is not a session");
+ await selectSession(target.sessionId);
+ };
+
+ const createSessionForProject = async (callId: string, selectionRef: string) => {
+ const target = await liveVoiceApi.resolveWorkSelection({ callId, selectionRef });
+ if (target.kind !== "project") throw new Error("The selected item is not a project");
+ await createSession({ projectPath: target.projectPath });
+ };
+
+ return (
+ <AnchoredMenu
+ open={open}
+ onClose={onClose}
+ anchorRef={anchorRef}
+ trigger={() => null}
+ role="dialog"
+ label={t("liveVoice.details")}
+ side="top"
+ align="end"
+ menuClassName="live-voice-popup live-voice-details-popup"
+ >
+ <Panel className="live-voice-details">
+ <div className="live-voice-panel-heading">
+ <strong>{t("liveVoice.details")}</strong>
+ <TooltipButton type="button" className="icon-btn icon-btn-square" tooltip={t("common.close")} onClick={onClose}>
+ <IconClose size={15} aria-hidden="true" />
+ </TooltipButton>
+ </div>
+ <div className="live-voice-service-label">
+ <span className="live-voice-hint">{t("liveVoice.provider")}</span>
+ <strong>{provider?.providerLabel ?? t("liveVoice.providerUnavailable")}</strong>
+ <span className="live-voice-hint">{t(`liveVoice.adapters.${call.adapterId}.title`)}</span>
+ </div>
+ {workBinding ? (
+ <section className="live-voice-work-setup">
+ <div className="live-voice-service-row">
+ <span>{t("liveVoice.boundWorkSession", { label: workBinding.label || t("liveVoice.untitledWorkSession") })}</span>
+ <TooltipButton
+ type="button"
+ className="icon-btn icon-btn-square"
+ tooltip={t("liveVoice.viewWorkSession")}
+ onClick={() => void selectSession(workBinding.workSessionId).catch(() => setMessage(t("liveVoice.sessionOpenFailed")))}
+ >
+ <IconExternal size={15} aria-hidden="true" />
+ </TooltipButton>
+ </div>
+ <p className="live-voice-hint">{t(workBinding.contextEnabled ? "liveVoice.contextShared" : "liveVoice.contextNotShared")}</p>
+ {activeSessionId !== workBinding.workSessionId ? (
+ <p className="live-voice-hint">{t("liveVoice.viewingDifferentSession", {
+ label: viewingSession
+ ? formatWorkSessionLabel(viewingSession.projectPath, viewingSession.title, t("liveVoice.untitledWorkSession"))
+ : t("liveVoice.unknownSession"),
+ })}</p>
+ ) : null}
+ {call.workOperations?.length ? (
+ <LiveWorkOperations
+ callId={call.callId}
+ sessionId={workBinding.workSessionId}
+ operations={call.workOperations}
+ t={t}
+ busyOperationId={busyOperationId}
+ setBusyOperationId={setBusyOperationId}
+ setMessage={setMessage}
+ onOpenSelection={openSelection}
+ onCreateSession={createSessionForProject}
+ />
+ ) : null}
+ </section>
+ ) : null}
+ {message ? <p className="live-voice-hint" role="status">{message}</p> : null}
+ <section aria-label={t("liveVoice.transcript")} className="live-voice-transcript-section">
+ <span className="live-voice-hint">{t("liveVoice.transcript")}</span>
+ {transcripts.length ? (
+ <div className="live-voice-transcripts selectable" aria-live="polite" aria-relevant="additions text">
+ {transcripts.map((segment) => (
+ <p key={`${segment.role}:${segment.id}`} data-role={segment.role}>{segment.text}</p>
+ ))}
+ </div>
+ ) : <p className="live-voice-hint">{t("liveVoice.transcriptEmpty")}</p>}
+ </section>
+ </Panel>
+ </AnchoredMenu>
+ );
+}
diff --git a/apps/desktop/src/features/voice/live/LiveVoicePreparation.tsx b/apps/desktop/src/features/voice/live/LiveVoicePreparation.tsx
new file mode 100644
index 000000000..6925ca94d
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/LiveVoicePreparation.tsx
@@ -0,0 +1,147 @@
+import { useEffect, useId, useState } from "react";
+import type { TFunction } from "i18next";
+import type { LiveStatus } from "@pi-desktop/shared";
+import { IconCheck, IconChevronDown, IconClose, IconLink, IconPlay, IconPlus, IconSettings } from "../../../components/icons";
+import { Button, Checkbox, Panel, Select, TooltipButton } from "../../../components/ui";
+import { useAppStore } from "../../../stores/app-store";
+import { getLiveCallController } from "./live-call-controller";
+import { openLiveVoiceSettings } from "./live-voice-navigation";
+import { formatWorkSessionLabel, liveReadinessMessage, selectedLiveBinding } from "./live-voice-presentation";
+
+export function LiveVoicePreparation({
+ t,
+ status,
+ workSessionId,
+ onClose,
+}: {
+ t: TFunction;
+ status: LiveStatus | null;
+ workSessionId?: string;
+ onClose: () => void;
+}) {
+ const sessions = useAppStore((state) => state.sessions);
+ const createSession = useAppStore((state) => state.newSession);
+ const [workExpanded, setWorkExpanded] = useState(false);
+ const [allowWork, setAllowWork] = useState(false);
+ const [selectedSessionId, setSelectedSessionId] = useState(workSessionId ?? "");
+ const [contextEnabled, setContextEnabled] = useState(false);
+ const [creating, setCreating] = useState(false);
+ const [createFailed, setCreateFailed] = useState(false);
+ useEffect(() => {
+ setSelectedSessionId(workSessionId ?? "");
+ setContextEnabled(false);
+ }, [workSessionId]);
+ const workId = useId();
+ const consentId = useId();
+ const localSessions = sessions.filter((session) => session.source === undefined || session.source === "desktop");
+ const selectedSession = localSessions.find((session) => session.id === selectedSessionId);
+ const binding = selectedLiveBinding(status);
+ const readinessMessage = liveReadinessMessage(status);
+ const workUnavailable = allowWork && !selectedSession;
+
+ const createWorkSession = async () => {
+ setCreating(true);
+ setCreateFailed(false);
+ try {
+ await createSession();
+ const id = useAppStore.getState().activeSessionId;
+ if (id) setSelectedSessionId(id);
+ else setCreateFailed(true);
+ setContextEnabled(false);
+ } catch {
+ setCreateFailed(true);
+ } finally {
+ setCreating(false);
+ }
+ };
+
+ return (
+ <Panel className="live-voice-preparation">
+ <div className="live-voice-panel-heading">
+ <strong>{t("liveVoice.prepareCall")}</strong>
+ <TooltipButton type="button" className="icon-btn icon-btn-square" tooltip={t("common.close")} onClick={onClose}>
+ <IconClose size={15} aria-hidden="true" />
+ </TooltipButton>
+ </div>
+ <div className="live-voice-service-row">
+ <div className="live-voice-service-label">
+ <span className="live-voice-hint">{t("liveVoice.provider")}</span>
+ <strong>{binding?.providerLabel ?? t("liveVoice.chooseProvider")}</strong>
+ </div>
+ <TooltipButton type="button" className="icon-btn icon-btn-square" tooltip={t("errors.action.openSettings")} onClick={() => { onClose(); openLiveVoiceSettings(); }}>
+ <IconSettings size={16} aria-hidden="true" />
+ </TooltipButton>
+ </div>
+ {readinessMessage ? <p className="live-voice-hint" role="status">{t(readinessMessage)}</p> : null}
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="live-voice-work-disclosure"
+ aria-expanded={workExpanded}
+ aria-controls={workId}
+ onClick={() => setWorkExpanded((value) => !value)}
+ >
+ <IconLink size={15} aria-hidden="true" />
+ <span>{t("liveVoice.workOptions")}</span>
+ {allowWork ? <IconCheck size={14} aria-hidden="true" /> : null}
+ <IconChevronDown size={14} className={workExpanded ? "is-expanded" : undefined} aria-hidden="true" />
+ </Button>
+ {workExpanded ? (
+ <div className="live-voice-work-setup" id={workId}>
+ <Checkbox
+ checked={allowWork}
+ label={t("liveVoice.allowWork")}
+ onChange={(event) => { setAllowWork(event.currentTarget.checked); setContextEnabled(false); }}
+ />
+ {allowWork ? (
+ <>
+ <Select
+ value={selectedSession?.id ?? ""}
+ aria-label={t("liveVoice.selectWorkSession")}
+ disabled={creating}
+ onChange={(event) => { setSelectedSessionId(event.currentTarget.value); setContextEnabled(false); }}
+ >
+ <option value="">{t("liveVoice.selectWorkSession")}</option>
+ {localSessions.map((session) => (
+ <option key={session.id} value={session.id}>
+ {formatWorkSessionLabel(session.projectPath, session.title, t("liveVoice.untitledWorkSession"))}
+ </option>
+ ))}
+ </Select>
+ <Checkbox
+ checked={contextEnabled}
+ disabled={!selectedSession || creating}
+ label={t("liveVoice.shareContext")}
+ aria-describedby={consentId}
+ onChange={(event) => setContextEnabled(event.currentTarget.checked)}
+ />
+ <p id={consentId} className="live-voice-hint">{t("liveVoice.contextConsent")}</p>
+ <TooltipButton type="button" className="icon-btn icon-btn-square" tooltip={t("liveVoice.createWorkSession")} disabled={creating} onClick={() => void createWorkSession()}>
+ {creating ? <span className="voice-spinner" aria-hidden="true" /> : <IconPlus size={15} aria-hidden="true" />}
+ </TooltipButton>
+ </>
+ ) : null}
+ </div>
+ ) : null}
+ {workUnavailable ? <p className="live-voice-hint" role="status">{t("liveVoice.noWorkSession")}</p> : null}
+ {createFailed ? <p className="live-voice-error" role="alert">{t("liveVoice.sessionCreateFailed")}</p> : null}
+ <Button
+ type="button"
+ variant="primary"
+ className="live-voice-start"
+ disabled={Boolean(readinessMessage) || workUnavailable || creating}
+ onClick={() => {
+ const options = allowWork && selectedSession
+ ? { workTarget: { workSessionId: selectedSession.id, contextEnabled } }
+ : {};
+ void getLiveCallController().start(options).catch(() => undefined);
+ onClose();
+ }}
+ >
+ <IconPlay size={16} aria-hidden="true" />
+ {t("liveVoice.start")}
+ </Button>
+ </Panel>
+ );
+}
diff --git a/apps/desktop/src/features/voice/live/LiveVoiceStatusHost.tsx b/apps/desktop/src/features/voice/live/LiveVoiceStatusHost.tsx
new file mode 100644
index 000000000..6b4e18866
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/LiveVoiceStatusHost.tsx
@@ -0,0 +1,96 @@
+import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react";
+import { useTranslation } from "react-i18next";
+import { useAppStore } from "../../../stores/app-store";
+import { getLiveCallController } from "./live-call-controller";
+import { openLiveVoiceSettings } from "./live-voice-navigation";
+import { hasUnconfirmedMediaRelease, liveVoiceIssue, liveVoiceMode } from "./live-voice-presentation";
+import { LiveVoiceCallBar } from "./LiveVoiceCallBar";
+import { LiveVoiceDetails } from "./LiveVoiceDetails";
+import "../../../styles/voice.css";
+
+/** Call chrome survives route changes; mounting it never owns or starts media. */
+export function LiveVoiceStatusHost() {
+ const { t } = useTranslation();
+ const page = useAppStore((state) => state.page);
+ const controller = getLiveCallController();
+ const snapshot = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
+ const [detailsOpen, setDetailsOpen] = useState(false);
+ const [dismissedIssue, setDismissedIssue] = useState<string | null>(null);
+ const [actionPending, setActionPending] = useState<"mute" | "playback" | null>(null);
+ const [actionFailure, setActionFailure] = useState<{ callId?: string; code: string } | null>(null);
+ const hostRef = useRef<HTMLDivElement>(null);
+ const detailsRef = useRef<HTMLButtonElement>(null);
+ const mode = liveVoiceMode(snapshot);
+ const previousMode = useRef(mode);
+ const callId = snapshot.call?.callId;
+ const issue = liveVoiceIssue(actionFailure && actionFailure.callId === callId
+ ? { ...snapshot, errorCode: snapshot.errorCode ?? actionFailure.code }
+ : snapshot);
+ const closeDetails = useCallback(() => setDetailsOpen(false), []);
+
+ useEffect(() => {
+ setDetailsOpen(false);
+ setDismissedIssue(null);
+ setActionFailure(null);
+ setActionPending(null);
+ }, [callId]);
+
+ useEffect(() => {
+ if (mode === "connecting") setDismissedIssue(null);
+ if (mode === "stopping" || mode === "idle") setDetailsOpen(false);
+ if ((mode === "connecting" && previousMode.current === "idle") ||
+ (mode === "connected" && document.activeElement === document.body)) {
+ hostRef.current?.querySelector<HTMLButtonElement>("button:not(:disabled)")?.focus();
+ }
+ previousMode.current = mode;
+ }, [mode]);
+
+ const runAction = (action: () => Promise<void>, pending?: "mute" | "playback") => {
+ setActionFailure(null);
+ if (pending) setActionPending(pending);
+ void action().catch(() => {
+ if (controller.getSnapshot().call?.callId === callId) {
+ setActionFailure({ callId, code: pending === "playback" ? "LIVE_PLAYBACK_FAILED" : "LIVE_CALL_ACTION_FAILED" });
+ }
+ }).finally(() => {
+ if (controller.getSnapshot().call?.callId === callId) setActionPending(null);
+ });
+ };
+
+ const releaseUnconfirmed = hasUnconfirmedMediaRelease(snapshot);
+ const hasVisibleIssue = issue && (releaseUnconfirmed || issue.key !== dismissedIssue) &&
+ (snapshot.status?.enabled === true || snapshot.call?.error || releaseUnconfirmed);
+ if (mode === "idle" && !hasVisibleIssue) return null;
+
+ return (
+ <div ref={hostRef} className="live-voice-status-host" data-chat={page === "chat"} role="region" aria-label={t("liveVoice.title")}>
+ <LiveVoiceCallBar
+ t={t}
+ snapshot={snapshot}
+ issue={issue}
+ detailsOpen={detailsOpen}
+ detailsRef={detailsRef}
+ actionPending={actionPending}
+ onCancel={() => runAction(() => snapshot.starting ? controller.cancelStart() : controller.end())}
+ onMute={() => runAction(() => controller.toggleMute(), "mute")}
+ onEnd={() => runAction(() => controller.end())}
+ onDetails={() => setDetailsOpen((value) => !value)}
+ onResume={() => runAction(() => controller.resumePlayback(), "playback")}
+ onSettings={openLiveVoiceSettings}
+ onDismiss={() => { setDismissedIssue(issue?.key ?? null); setDetailsOpen(false); }}
+ />
+ {snapshot.call ? (
+ <LiveVoiceDetails
+ key={snapshot.call.callId}
+ t={t}
+ call={snapshot.call}
+ status={snapshot.status}
+ transcripts={snapshot.transcripts}
+ open={detailsOpen}
+ onClose={closeDetails}
+ anchorRef={detailsRef}
+ />
+ ) : null}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/voice/live/live-call-controller.ts b/apps/desktop/src/features/voice/live/live-call-controller.ts
index 6eaaeb0e1..4570cbb6d 100644
--- a/apps/desktop/src/features/voice/live/live-call-controller.ts
+++ b/apps/desktop/src/features/voice/live/live-call-controller.ts
@@ -21,6 +21,7 @@ export type LiveVoiceSnapshot = {
call: LiveCallView | null;
transcripts: LiveTranscriptSegment[];
starting: boolean;
+ stopping: boolean;
errorCode?: string;
};
@@ -29,6 +30,7 @@ const EMPTY_SNAPSHOT: LiveVoiceSnapshot = {
call: null,
transcripts: [],
starting: false,
+ stopping: false,
};
const MAX_TRANSCRIPTS = 40;
const ICE_GATHER_TIMEOUT_MS = 10_000;
@@ -50,7 +52,12 @@ type StartResources = {
playbackActive?: boolean;
heartbeat?: ReturnType<typeof setInterval>;
captureEpoch: number;
- releasePromise?: Promise<void>;
+ releasePromise?: Promise<boolean>;
+ releaseReportPromise?: Promise<void>;
+ localReleaseSettled?: boolean;
+ mainTerminationSettled?: boolean;
+ releaseAckSettled?: boolean;
+ releaseFailed?: boolean;
abort: AbortController;
completedControlActions?: Set<string>;
};
@@ -106,7 +113,11 @@ export class LiveCallController {
}
async start(options: { workTarget?: { workSessionId: string; contextEnabled: boolean } } = {}): Promise<void> {
- if (this.snapshot.starting || isLive(this.snapshot.call?.phase)) return;
+ if (this.snapshot.starting || this.snapshot.stopping || isLive(this.snapshot.call?.phase)) return;
+ if (this.snapshot.call?.error?.code === "LIVE_MEDIA_RELEASE_UNCONFIRMED" || this.snapshot.errorCode === "LIVE_MEDIA_RELEASE_UNCONFIRMED") {
+ this.patch({ errorCode: "LIVE_MEDIA_RELEASE_UNCONFIRMED" });
+ throw liveError("LIVE_MEDIA_RELEASE_UNCONFIRMED");
+ }
const generation = ++this.generation;
const cachedStatus = this.snapshot.status;
if (!cachedStatus?.enabled) throw liveError("LIVE_DISABLED");
@@ -117,7 +128,7 @@ export class LiveCallController {
const requestId = crypto.randomUUID();
const resources: StartResources = { requestId, abort: new AbortController(), captureEpoch: 0, completedControlActions: new Set() };
this.resources.set(requestId, resources);
- this.patch({ starting: true, errorCode: undefined, transcripts: [] });
+ this.patch({ starting: true, stopping: false, errorCode: undefined, transcripts: [] });
let prepareRequest: ReturnType<typeof liveVoiceApi.prepare> | undefined;
let micRequest: Promise<MediaStream> | undefined;
@@ -197,15 +208,29 @@ export class LiveCallController {
}, 5_000);
} catch (error) {
void micRequest?.then((stream) => stopStream(stream)).catch(() => undefined);
- if (resources.callId) {
- await liveVoiceApi.end({ callId: resources.callId, reason: resources.abort.signal.aborted ? "user-cancelled-start" : "network-error" }).catch(() => undefined);
- } else {
- await liveVoiceApi.end({ requestId, reason: "user-cancelled-start" }).catch(() => undefined);
+ try {
+ if (resources.callId) {
+ await liveVoiceApi.end({ callId: resources.callId, reason: resources.abort.signal.aborted ? "user-cancelled-start" : "network-error" });
+ } else {
+ await liveVoiceApi.end({ requestId, reason: "user-cancelled-start" });
+ resources.mainTerminationSettled = true;
+ }
+ } catch (endError) {
+ this.patch({ errorCode: errorCode(endError) });
}
await this.releaseResources(resources, Boolean(resources.callId));
- this.resources.delete(requestId);
- if (resources.callId) this.resources.delete(resources.callId);
- this.patch({ starting: false, call: null, errorCode: errorCode(error) });
+ const currentCall = this.snapshot.call;
+ const terminalCall = currentCall?.phase === "ended" || currentCall?.phase === "failed";
+ const preserveCall = terminalCall && (!resources.callId || resources.callId === currentCall.callId);
+ const cancelled = resources.abort.signal.aborted && (generation !== this.generation || this.snapshot.stopping);
+ this.patch({
+ starting: false,
+ ...(preserveCall ? {} : { call: null }),
+ ...(!cancelled
+ ? { errorCode: resources.releaseFailed ? "LIVE_MEDIA_RELEASE_UNCONFIRMED" : currentCall?.error?.code ?? errorCode(error) }
+ : resources.releaseFailed ? { errorCode: "LIVE_MEDIA_RELEASE_UNCONFIRMED" } : {}),
+ });
+ this.completeResourceLifecycle(resources);
throw error;
} finally {
if (this.snapshot.starting && generation === this.generation && !resources.callId) this.patch({ starting: false });
@@ -217,16 +242,24 @@ export class LiveCallController {
if (!resource) return;
this.generation += 1;
resource.abort.abort();
- if (resource.callId) await liveVoiceApi.end({ callId: resource.callId, reason: "user-cancelled-start" }).catch(() => undefined);
- else await liveVoiceApi.end({ requestId: resource.requestId, reason: "user-cancelled-start" }).catch(() => undefined);
+ this.patch({ starting: false, stopping: true });
+ try {
+ if (resource.callId) await liveVoiceApi.end({ callId: resource.callId, reason: "user-cancelled-start" });
+ else {
+ await liveVoiceApi.end({ requestId: resource.requestId, reason: "user-cancelled-start" });
+ resource.mainTerminationSettled = true;
+ resource.releaseAckSettled = true;
+ }
+ } catch (error) {
+ this.patch({ errorCode: errorCode(error) });
+ }
await this.releaseResources(resource, Boolean(resource.callId));
- this.resources.delete(resource.requestId);
- this.patch({ starting: false });
+ this.completeResourceLifecycle(resource);
}
async toggleMute(): Promise<void> {
const call = this.snapshot.call;
- if (!call || call.phase !== "connected") return;
+ if (this.snapshot.stopping || !call || call.phase !== "connected") return;
const resources = this.resources.get(call.callId);
if (!resources) return;
const muted = !call.muted;
@@ -247,7 +280,7 @@ export class LiveCallController {
async resumePlayback(): Promise<void> {
const call = this.snapshot.call;
- if (!call) return;
+ if (this.snapshot.stopping || !call) return;
const resources = this.resources.get(call.callId);
if (!resources) return;
try {
@@ -263,7 +296,25 @@ export class LiveCallController {
async end(): Promise<void> {
const call = this.snapshot.call;
if (!call) return this.cancelStart();
- await liveVoiceApi.end({ callId: call.callId, reason: "user-ended" }).catch((error) => this.patch({ errorCode: errorCode(error) }));
+ const resources = this.resources.get(call.callId);
+ this.patch({ stopping: true });
+ try {
+ await liveVoiceApi.end({ callId: call.callId, reason: "user-ended" });
+ const latest = this.snapshot.call;
+ if (resources && latest?.callId === call.callId && (latest.phase === "ended" || latest.phase === "failed")) {
+ resources.mainTerminationSettled = true;
+ if (!resources.releaseReportPromise) resources.releaseAckSettled = true;
+ this.completeResourceLifecycle(resources);
+ } else if (!resources && latest?.callId === call.callId && (latest.phase === "ended" || latest.phase === "failed")) {
+ this.patch({ stopping: false });
+ }
+ } catch (error) {
+ const latest = this.snapshot.call;
+ const awaitingRelease = resources
+ ? !resources.localReleaseSettled || !resources.mainTerminationSettled || Boolean(resources.callId && !resources.releaseAckSettled)
+ : latest?.callId === call.callId && latest.phase === "closing";
+ this.patch({ errorCode: errorCode(error), stopping: awaitingRelease });
+ }
}
private async connectWebRtc(callId: string, resources: StartResources): Promise<void> {
@@ -468,26 +519,31 @@ export class LiveCallController {
if (this.terminalCallIds.has(view.callId)) return;
const current = this.snapshot.call;
if (current?.callId === view.callId && view.revision < current.revision) return;
- const resources = this.resources.get(view.callId) ?? (this.snapshot.starting && view.phase === "preparing"
+ const resources = this.resources.get(view.callId) ?? (view.phase === "preparing"
? [...this.resources.values()].find((item) => !item.callId)
: undefined);
if (resources && !resources.callId) {
resources.callId = view.callId;
this.resources.set(view.callId, resources);
}
- this.patch({ call: view });
- if (resources && (view.phase === "ended" || view.phase === "failed")) {
- this.terminalCallIds.add(view.callId);
- while (this.terminalCallIds.size > 16) this.terminalCallIds.delete(this.terminalCallIds.values().next().value as string);
- void this.releaseResources(resources, true).finally(() => {
- this.resources.delete(resources.requestId);
- this.resources.delete(view.callId);
- this.patch({ starting: false });
- });
- } else if (view.phase === "ended" || view.phase === "failed") {
+ if (view.phase === "closing") {
+ this.patch({ call: view, stopping: true });
+ return;
+ }
+ if (view.phase === "ended" || view.phase === "failed") {
this.terminalCallIds.add(view.callId);
while (this.terminalCallIds.size > 16) this.terminalCallIds.delete(this.terminalCallIds.values().next().value as string);
+ if (resources) {
+ resources.mainTerminationSettled = true;
+ if (!resources.releaseReportPromise) resources.releaseAckSettled = true;
+ this.patch({ call: view, stopping: !resources.localReleaseSettled || !resources.releaseAckSettled });
+ void this.releaseResources(resources, view.mediaRelease === "pending").then(() => this.completeResourceLifecycle(resources));
+ } else {
+ this.patch({ call: view, starting: false, stopping: false });
+ }
+ return;
}
+ this.patch({ call: view });
}
private handleControl(event: LiveControlEvent): void {
@@ -608,30 +664,74 @@ export class LiveCallController {
await liveVoiceApi.end({ callId, reason: "network-error" }).catch(() => undefined);
}
- private async releaseResources(resources: StartResources, notifyMain: boolean): Promise<void> {
- if (resources.releasePromise) return resources.releasePromise;
- resources.releasePromise = this.releaseResourcesOnce(resources, notifyMain);
- return resources.releasePromise;
+ private releaseResources(resources: StartResources, notifyMain: boolean): Promise<void> {
+ if (!resources.releasePromise) {
+ resources.releasePromise = this.releaseResourcesOnce(resources).then((released) => {
+ resources.localReleaseSettled = true;
+ if (!released) {
+ resources.releaseFailed = true;
+ this.patch({ errorCode: "LIVE_MEDIA_RELEASE_UNCONFIRMED" });
+ }
+ this.completeResourceLifecycle(resources);
+ return released;
+ });
+ }
+ if (notifyMain && resources.callId && !resources.releaseReportPromise) {
+ resources.releaseReportPromise = resources.releasePromise.then(async (released) => {
+ if (!released) {
+ resources.releaseAckSettled = true;
+ this.completeResourceLifecycle(resources);
+ return;
+ }
+ try {
+ await liveVoiceApi.reportMedia({ callId: resources.callId!, kind: "released" });
+ } catch {
+ resources.releaseFailed = true;
+ this.patch({ errorCode: "LIVE_MEDIA_RELEASE_UNCONFIRMED" });
+ } finally {
+ resources.releaseAckSettled = true;
+ this.completeResourceLifecycle(resources);
+ }
+ });
+ }
+ return resources.releaseReportPromise ?? resources.releasePromise.then(() => undefined);
}
- private async releaseResourcesOnce(resources: StartResources, notifyMain: boolean): Promise<void> {
+ private async releaseResourcesOnce(resources: StartResources): Promise<boolean> {
+ let released = true;
+ const cleanup = (action: () => void) => {
+ try { action(); } catch { released = false; }
+ };
+ const cleanupAsync = async (action: () => Promise<unknown> | undefined) => {
+ try { await action(); } catch { released = false; }
+ };
if (resources.heartbeat) clearInterval(resources.heartbeat);
resources.abort.abort();
- this.stopPlaybackMonitor(resources);
- resources.stream && stopStream(resources.stream);
- resources.channel?.close();
- resources.peer?.close();
- if (resources.audio) {
- resources.audio.pause();
- resources.audio.srcObject = null;
- resources.audio.remove();
+ cleanup(() => this.stopPlaybackMonitor(resources));
+ if (resources.stream) cleanup(() => stopStream(resources.stream!));
+ if (resources.channel) cleanup(() => resources.channel!.close());
+ if (resources.peer) cleanup(() => resources.peer!.close());
+ if (resources.audio) cleanup(() => {
+ resources.audio!.pause();
+ resources.audio!.srcObject = null;
+ resources.audio!.remove();
+ });
+ if (resources.pcm) await cleanupAsync(() => resources.pcm?.release());
+ if (!resources.pcm && resources.context && resources.context.state !== "closed") {
+ await cleanupAsync(() => resources.context?.close());
}
- await resources.pcm?.release().catch(() => undefined);
- if (!resources.pcm && resources.context && resources.context.state !== "closed") await resources.context.close().catch(() => undefined);
- if (notifyMain && resources.callId) {
- await liveVoiceApi.reportMedia({ callId: resources.callId, kind: "released" }).catch(() => undefined);
+ if (resources.port && resources.pcm === undefined) cleanup(() => resources.port!.close());
+ return released;
+ }
+
+ private completeResourceLifecycle(resources: StartResources): void {
+ if (!resources.localReleaseSettled || !resources.mainTerminationSettled) return;
+ if (resources.callId && !resources.releaseAckSettled) return;
+ if (!resources.callId || this.snapshot.call?.callId === resources.callId) {
+ this.patch({ starting: false, stopping: false });
}
- if (resources.port && resources.pcm === undefined) resources.port.close();
+ this.resources.delete(resources.requestId);
+ if (resources.callId) this.resources.delete(resources.callId);
}
private readonly handlePageHide = (): void => {
diff --git a/apps/desktop/src/features/voice/live/live-voice-navigation.ts b/apps/desktop/src/features/voice/live/live-voice-navigation.ts
new file mode 100644
index 000000000..1130eb9f2
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/live-voice-navigation.ts
@@ -0,0 +1,13 @@
+import { isSettingsDestinationHidden } from "../../../lib/settings-search";
+import { useAppStore } from "../../../stores/app-store";
+
+export function openLiveVoiceSettings() {
+ const store = useAppStore.getState();
+ const voiceHidden = isSettingsDestinationHidden(
+ "voice",
+ store.settings?.developerMode === true,
+ import.meta.env.DEV,
+ );
+ store.setSettingsTab(voiceHidden ? "agent" : "voice");
+ store.setPage("settings");
+}
diff --git a/apps/desktop/src/features/voice/live/live-voice-presentation.ts b/apps/desktop/src/features/voice/live/live-voice-presentation.ts
new file mode 100644
index 000000000..0cbc5429e
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/live-voice-presentation.ts
@@ -0,0 +1,74 @@
+import type { LiveStatus } from "@pi-desktop/shared";
+import type { LiveVoiceSnapshot } from "./live-call-controller";
+
+export type LiveVoiceMode = "idle" | "connecting" | "reconnecting" | "connected" | "stopping";
+
+export function liveVoiceMode(snapshot: LiveVoiceSnapshot): LiveVoiceMode {
+ if (snapshot.stopping || snapshot.call?.phase === "closing") return "stopping";
+ if (snapshot.starting) return "connecting";
+ switch (snapshot.call?.phase) {
+ case "connected": return "connected";
+ case "reconnecting": return "reconnecting";
+ case "preparing":
+ case "acquiring-mic":
+ case "negotiating":
+ case "connecting": return "connecting";
+ default: return "idle";
+ }
+}
+
+export function hasUnconfirmedMediaRelease(snapshot: LiveVoiceSnapshot): boolean {
+ return snapshot.call?.error?.code === "LIVE_MEDIA_RELEASE_UNCONFIRMED" || snapshot.errorCode === "LIVE_MEDIA_RELEASE_UNCONFIRMED";
+}
+
+export function selectedLiveBinding(status: LiveStatus | null) {
+ return status?.bindings.find((binding) => binding.bindingId === status.selectedBindingId);
+}
+
+export function liveReadinessMessage(status: LiveStatus | null): string | null {
+ if (!status?.enabled) return "liveVoice.enableInSettings";
+ const binding = selectedLiveBinding(status);
+ if (!binding) return "liveVoice.noProvider";
+ if (!binding.selectable) return `liveVoice.readiness.${binding.reason ?? "invalid-settings"}`;
+ return null;
+}
+
+const ERROR_MESSAGES: Record<string, string> = {
+ LIVE_MICROPHONE_DENIED: "liveVoice.microphoneDenied",
+ LIVE_MICROPHONE_BUSY: "liveVoice.microphoneBusy",
+ LIVE_MICROPHONE_UNAVAILABLE: "liveVoice.microphoneUnavailable",
+ LIVE_MEDIA_RELEASE_UNCONFIRMED: "liveVoice.mediaReleaseUnconfirmed",
+ LIVE_PLAYBACK_BLOCKED: "liveVoice.playbackBlocked",
+ LIVE_PLAYBACK_FAILED: "liveVoice.playbackFailed",
+ LIVE_NOT_CONFIGURED: "liveVoice.noProvider",
+ LIVE_DISABLED: "liveVoice.enableInSettings",
+ LIVE_EXECUTION_NOT_CONNECTED: "liveVoice.workNotConnected",
+ LIVE_CALL_ACTION_FAILED: "liveVoice.callActionFailed",
+};
+
+export function liveVoiceIssue(snapshot: LiveVoiceSnapshot) {
+ const { call } = snapshot;
+ const terminal = call?.phase === "ended" || call?.phase === "failed" || call?.phase === "idle";
+ const notice = terminal || (call?.notice?.code === "LIVE_PLAYBACK_BLOCKED" && !call.playbackBlocked)
+ ? undefined
+ : call?.notice?.code;
+ const code = call?.error?.code === "LIVE_MEDIA_RELEASE_UNCONFIRMED" || snapshot.errorCode === "LIVE_MEDIA_RELEASE_UNCONFIRMED"
+ ? "LIVE_MEDIA_RELEASE_UNCONFIRMED"
+ : call?.error?.code ?? snapshot.errorCode ?? notice
+ ?? (!terminal && call?.playbackBlocked ? "LIVE_PLAYBACK_BLOCKED" : undefined);
+ if (!code) return null;
+ return {
+ code,
+ key: `${call?.callId ?? "start"}:${code}`,
+ message: ERROR_MESSAGES[code] ?? (code.startsWith("LIVE_WORK_")
+ ? "liveVoice.workActionFailed"
+ : call?.phase === "connected" ? "liveVoice.callActionFailed" : "liveVoice.errorGeneric"),
+ warning: code === "LIVE_PLAYBACK_BLOCKED",
+ };
+}
+
+export function formatWorkSessionLabel(projectPath: string | undefined, title: string, untitledLabel: string) {
+ const projectLabel = projectPath?.split(/[\\/]/).filter(Boolean).at(-1);
+ const sessionLabel = title.trim() || untitledLabel;
+ return projectLabel ? `${projectLabel} / ${sessionLabel}` : sessionLabel;
+}
diff --git a/apps/desktop/src/styles/voice.css b/apps/desktop/src/styles/voice.css
index 060c343f2..6d6fc5d97 100644
--- a/apps/desktop/src/styles/voice.css
+++ b/apps/desktop/src/styles/voice.css
@@ -119,46 +119,169 @@
position: relative;
}
-.live-voice-panel {
- position: absolute;
- left: 0;
- bottom: calc(100% + 8px);
- z-index: 20;
+.live-voice-popup {
+ position: fixed;
+ z-index: 60;
+ visibility: hidden;
width: min(360px, calc(100vw - 32px));
+ max-height: min(560px, calc(100dvh - 32px));
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ border: 1px solid var(--ds-border-subtle);
+ border-radius: var(--radius-sm);
+ background: var(--ds-bg-elevated-opaque);
+ box-shadow: var(--ds-shadow-dialog);
+ color: var(--ds-text-primary);
}
-.live-voice-panel .live-voice-panel-surface {
+.live-voice-popup.is-open {
+ visibility: visible;
+}
+
+.live-voice-preparation,
+.live-voice-details {
display: grid;
gap: 12px;
- padding: 14px 16px;
+ padding: 12px;
+ border: 0;
+ background: transparent;
+ box-shadow: none;
+}
+
+.live-voice-preparation p,
+.live-voice-details p {
+ margin: 0;
+}
+
+.live-voice-panel-heading,
+.live-voice-service-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+
+.live-voice-panel-heading strong,
+.live-voice-service-label strong {
+ color: var(--ds-text-primary);
+ font-size: var(--text-md);
+}
+
+.live-voice-service-label,
+.live-voice-transcript-section {
+ display: grid;
+ gap: 4px;
+ min-width: 0;
+ overflow-wrap: anywhere;
+}
+
+.live-voice-work-disclosure.btn {
+ justify-content: flex-start;
+ gap: 8px;
+ padding-inline: 0;
+ color: var(--ds-text-secondary);
+}
+
+.live-voice-work-disclosure svg:last-child {
+ margin-inline-start: auto;
+ transition: transform 140ms ease;
+}
+
+.live-voice-work-disclosure .is-expanded {
+ transform: rotate(180deg);
+}
+
+.live-voice-start.btn {
+ justify-content: center;
+ gap: 8px;
+}
+
+.live-voice-status-host {
+ position: fixed;
+ z-index: 35;
+ left: 50%;
+ bottom: 20px;
+ width: max-content;
+ max-width: calc(100vw - 32px);
+ transform: translateX(-50%);
+}
+
+.live-voice-status-host[data-chat="true"] {
+ bottom: calc(var(--composer-dock-height, 168px) + 12px);
+}
+
+.live-voice-call-bar {
+ max-width: 480px;
+ padding: 6px 8px;
border: 1px solid var(--ds-border-subtle);
border-radius: var(--radius-sm);
background: var(--ds-bg-elevated-opaque);
box-shadow: var(--ds-shadow-dialog);
color: var(--ds-text-primary);
+ font-size: var(--text-sm);
}
-.live-voice-panel-heading,
-.live-voice-actions {
+.live-voice-call-row,
+.live-voice-call-status,
+.live-voice-call-actions {
display: flex;
align-items: center;
gap: 8px;
}
-.live-voice-panel-heading {
+.live-voice-call-row {
justify-content: space-between;
+ gap: 16px;
}
-.live-voice-actions {
- justify-content: flex-end;
+.live-voice-call-status {
+ min-width: 0;
}
-.live-voice-panel-heading strong {
- color: var(--ds-text-primary);
- font-size: var(--text-md);
+.live-voice-call-status > svg,
+.live-voice-call-status > .voice-spinner,
+.live-voice-call-actions {
+ flex-shrink: 0;
+}
+
+.live-voice-status-text {
+ color: var(--ds-text-secondary);
+}
+
+.live-voice-call-actions {
+ gap: 2px;
+}
+
+.live-voice-call-actions .live-voice-end {
+ color: var(--ds-error);
+}
+
+.live-voice-call-actions .live-voice-muted {
+ color: var(--ds-text-secondary);
+ background: var(--ds-bg-active);
+}
+
+.live-voice-call-actions .live-voice-resume {
+ color: var(--ds-warning);
+}
+
+.live-voice-feedback {
+ margin: 4px 4px 2px 25px;
+ overflow-wrap: anywhere;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .live-voice-status-host .voice-spinner,
+ .live-voice-status-host .voice-mic-active,
+ .live-voice-preparation .voice-spinner {
+ animation: none;
+ }
+
+ .live-voice-work-disclosure svg:last-child {
+ transition: none;
+ }
}
-.live-voice-provider,
.live-voice-hint {
color: var(--ds-text-secondary);
font-size: var(--text-sm);
@@ -171,11 +294,6 @@
gap: 8px;
}
-.live-voice-field-label {
- color: var(--ds-text-secondary);
- font-size: var(--text-sm);
-}
-
.live-voice-work-operation {
display: flex;
align-items: center;
diff --git a/apps/desktop/test/fixtures/live-voice-interaction-runner.cjs b/apps/desktop/test/fixtures/live-voice-interaction-runner.cjs
new file mode 100644
index 000000000..dfd9d6f03
--- /dev/null
+++ b/apps/desktop/test/fixtures/live-voice-interaction-runner.cjs
@@ -0,0 +1,334 @@
+const { app, BrowserWindow } = require("electron");
+const { writeFileSync } = require("node:fs");
+const { join } = require("node:path");
+const assert = require("node:assert/strict");
+
+app.setName("PI Live Voice Interaction Test");
+const results = [];
+const deniedRequests = [];
+let permissionRequests = 0;
+let win;
+const artifact = (name) => join(process.env.PI_LIVE_VOICE_ARTIFACT_DIR, name);
+const prep = '[role="dialog"][aria-label="Prepare Live voice"]';
+const details = '[role="dialog"][aria-label="Call details"]';
+const bar = ".live-voice-call-bar";
+const button = (name, scope = "body") => `ui.named('button', ${JSON.stringify(name)}, ${JSON.stringify(scope)})`;
+const checkbox = (name) => `ui.named('input[type="checkbox"]', ${JSON.stringify(name)}, ${JSON.stringify(prep)})`;
+const evaluate = (code) => win.webContents.executeJavaScript(code);
+const frame = () => evaluate(`(async () => {
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ await Promise.all(document.getAnimations()
+ .filter(animation => animation.effect?.getComputedTiming().iterations !== Infinity)
+ .map(animation => animation.finished.catch(() => {})));
+})()`);
+
+async function wait(name, predicate) {
+ await evaluate(`new Promise((resolve, reject) => {
+ const deadline = performance.now() + 10000;
+ function poll() {
+ try {
+ const s = window.liveVoiceFixture?.inspect();
+ const ui = window.voiceTest;
+ if (${predicate}) return resolve(true);
+ if (performance.now() > deadline) return reject(new Error(${JSON.stringify(name)} + ': ' + JSON.stringify(s)));
+ requestAnimationFrame(poll);
+ } catch (error) { reject(error); }
+ }
+ poll();
+ })`);
+}
+async function check(name, predicate) {
+ await wait(name, predicate);
+ results.push({ name, ok: true });
+ console.log(`PASS ${name}`);
+}
+async function click(expression) {
+ const point = await evaluate(`(() => {
+ const ui = window.voiceTest;
+ const element = ${expression};
+ if (!element || element.disabled) throw new Error('Missing or disabled input: ' + ${JSON.stringify(expression)});
+ element.scrollIntoView({ block: 'nearest' });
+ const rect = element.getBoundingClientRect();
+ const x = Math.round(rect.x + rect.width / 2), y = Math.round(rect.y + rect.height / 2);
+ if (!ui.visible(element) || !element.contains(document.elementFromPoint(x, y))) throw new Error('Input is not reachable: ' + ${JSON.stringify(expression)});
+ return { x, y };
+ })()`);
+ win.webContents.sendInputEvent({ type: "mouseDown", button: "left", clickCount: 1, ...point });
+ win.webContents.sendInputEvent({ type: "mouseUp", button: "left", clickCount: 1, ...point });
+ await frame();
+}
+async function key(keyCode, modifiers = []) {
+ win.webContents.sendInputEvent({ type: "keyDown", keyCode, modifiers });
+ win.webContents.sendInputEvent({ type: "keyUp", keyCode, modifiers });
+ await frame();
+}
+async function fresh(enabled = true) {
+ await win.loadURL(process.env.PI_LIVE_VOICE_FIXTURE_URL);
+ await wait("fixture loaded", "s?.snapshot.status && document.querySelector('[aria-label=\"Fixture shell navigation\"]')");
+ await evaluate(`window.voiceTest = {
+ visible(element) {
+ if (!element || element.closest('[hidden]')) return false;
+ const rect = element.getBoundingClientRect();
+ const style = getComputedStyle(element);
+ return rect.width > 0 && rect.height > 0 && style.visibility !== 'hidden' && style.display !== 'none';
+ },
+ name(element) {
+ const labelled = element.getAttribute('aria-labelledby');
+ return (element.getAttribute('aria-label') || (labelled && labelled.split(/\\s+/).map(id => document.getElementById(id)?.textContent ?? '').join(' '))
+ || (element.labels?.length ? [...element.labels].map(label => label.textContent).join(' ') : element.textContent)).trim().replace(/\\s+/g, ' ');
+ },
+ all(selector, name, scope = 'body') {
+ return [...(document.querySelector(scope)?.querySelectorAll(selector) ?? [])]
+ .filter(element => this.visible(element) && (name === undefined || this.name(element) === name));
+ },
+ named(selector, name, scope = 'body') {
+ const matches = this.all(selector, name, scope);
+ if (matches.length > 1) throw new Error('Ambiguous accessible name: ' + name);
+ return matches[0];
+ },
+ state(value) { return this.visible(document.querySelector('.live-voice-call-bar[data-state="' + value + '"]')); },
+ dialog(selector) { return this.visible(document.querySelector(selector)); },
+ };`);
+ if (enabled) {
+ await evaluate("window.liveVoiceFixture.configure({ enabled: true })");
+ await wait("Live Voice enabled", `s.snapshot.status.enabled && ${button("Live voice")}`);
+ }
+}
+const noMedia = "['prepare','connect','getUserMedia','audioContext'].every(name => s.counts[name] === 0)";
+const noDialog = "document.querySelectorAll('[role=dialog]').length === 0";
+async function openPreparation() {
+ await click(button("Live voice"));
+ await wait("preparation open", `ui.dialog(${JSON.stringify(prep)})`);
+}
+async function start() {
+ await openPreparation();
+ await click(button("Start Live voice", prep));
+}
+async function connected() {
+ await wait("connected call", `ui.state('connected') && !s.snapshot.starting && s.snapshot.call?.phase === 'connected'`);
+}
+async function clean() {
+ await check("no unexpected IPC, browser errors, or surviving local media",
+ "s.requests.unexpected.length === 0 && s.errors.length === 0 && s.tracks.every(track => track.readyState === 'ended') && s.contexts.every(context => context.state === 'closed') && s.peers.every(peer => peer.connectionState === 'closed') && document.querySelectorAll('audio').length === 0");
+}
+
+async function preparationScenario() {
+ await fresh(false);
+ await check("disabled Live Voice has neither Live nor work icons",
+ `ui.all('button', undefined, '[data-fixture-composer]').length === 0 && !ui.visible(document.querySelector('.live-voice-status-host')) && ${noMedia}`);
+ await evaluate("window.liveVoiceFixture.configure({ enabled: true })");
+ await check("enabling exposes exactly one idle trigger",
+ `s.snapshot.status.enabled && ui.all('button', undefined, '[data-fixture-composer]').length === 1 && ${button("Live voice")}`);
+ await openPreparation();
+ await click(button("Connect a work session", prep));
+ await check("work disclosure is inert until explicit Start", `${checkbox("Allow work requests")}?.checked === false && ${noMedia}`);
+ await click(button("Close", prep));
+ await check("closing preparation acquires no media", `${noDialog} && ${noMedia}`);
+ await openPreparation();
+ await key("Escape");
+ await check("Escape dismisses preparation without starting", `${noDialog} && ${noMedia}`);
+ await openPreparation();
+ await click(button("Fixture chat route"));
+ await check("outside click dismisses preparation without starting", `${noDialog} && ${noMedia}`);
+ await openPreparation();
+ await click(button("Fixture toggle composer visibility"));
+ await check("hidden composer suppresses the production preparation portal",
+ `${noDialog} && !${button("Live voice")} && document.querySelector('[data-fixture-composer]')?.hidden && ${noMedia}`);
+ await click(button("Fixture toggle composer visibility"));
+ await evaluate("window.liveVoiceFixture.configure({ selectedAvailable: false })");
+ await wait("selected binding unavailable", "s.snapshot.status.bindings[0].selectable === false");
+ await openPreparation();
+ await check("unavailable exact selection explains failure despite another ready account",
+ `${button("Start Live voice", prep)}?.disabled && document.querySelector(${JSON.stringify(prep)})?.textContent.includes('Credentials missing') && s.snapshot.status.bindings[1].selectable && ${noMedia}`);
+ await key("Escape");
+ await clean();
+}
+
+async function cancellationScenario() {
+ await fresh();
+ await evaluate("['connect','end','released'].forEach(name => window.liveVoiceFixture.hold(name))");
+ await start();
+ await check("explicit Start defaults muted and shows compact connecting with Cancel",
+ `ui.state('connecting') && ${button("Cancel", bar)} && ${noDialog} && s.counts.connect === 1 && s.counts.prepare === 1 && s.counts.getUserMedia === 1 && s.counts.audioContext === 0 && s.requests.prepare[0].initialMuted === true && !s.requests.prepare[0].workTarget && s.tracks.every(track => !track.enabled)`);
+ await click(button("Cancel", bar));
+ await check("Cancel enters stopping while deferred release remains pending",
+ `ui.state('stopping') && s.snapshot.stopping && s.counts.released === 1 && s.tracks.every(track => track.readyState === 'ended') && !${button("Live voice")}`);
+ await evaluate("window.liveVoiceFixture.release('connect'); window.liveVoiceFixture.release('end')");
+ await check("terminal host result cannot hide pending renderer release",
+ `s.snapshot.call?.phase === 'ended' && s.snapshot.stopping && ui.state('stopping')`);
+ await evaluate("window.liveVoiceFixture.release('released')");
+ await check("cancel finishes neutrally without a reconnect",
+ `!s.snapshot.starting && !s.snapshot.stopping && !s.snapshot.errorCode && ${button("Live voice")} && !ui.visible(document.querySelector(${JSON.stringify(bar)})) && s.counts.prepare === 1 && s.counts.connect === 1`);
+ await clean();
+}
+
+async function connectedScenario() {
+ await fresh();
+ await start();
+ await connected();
+ await check("connected call starts muted with no details dialog", `${button("Unmute microphone", bar)} && s.snapshot.call.muted && ${noDialog}`);
+ await evaluate("window.liveVoiceFixture.setPhase('reconnecting')");
+ await check("reconnecting keeps an explicit End action", `ui.state('reconnecting') && ${button("End call", bar)} && !${button("Cancel", bar)} && !${button("Unmute microphone", bar)}`);
+ await evaluate("window.liveVoiceFixture.setPhase('connected')");
+ await connected();
+ await click(button("Unmute microphone", bar));
+ await check("unmute opens the real controller capture gate", `${button("Mute microphone", bar)} && !s.snapshot.call.muted && s.tracks[0].enabled && s.counts.mute === 1`);
+ await click(button("Mute microphone", bar));
+ await check("mute immediately closes the capture gate", `${button("Unmute microphone", bar)} && s.snapshot.call.muted && !s.tracks[0].enabled && s.counts.mute === 2`);
+ await evaluate("window.liveVoiceFixture.transcript('Fixture provider transcript')");
+ for (const method of ["Close", "Escape", "outside"]) {
+ await click(button("Call details", bar));
+ await wait("details show actual transcript", `ui.dialog(${JSON.stringify(details)}) && document.querySelector(${JSON.stringify(details)})?.textContent.includes('Fixture provider transcript')`);
+ if (method === "Close") await click(button("Close", details));
+ else if (method === "Escape") await key("Escape");
+ else await click(button("Fixture chat route"));
+ await check(`${method} dismisses details without ending the call`, `${noDialog} && ui.state('connected') && s.counts.end === 0`);
+ }
+ await key("Escape");
+ await check("Escape never ends a connected call", "ui.state('connected') && s.counts.end === 0");
+ await key("V", [process.platform === "darwin" ? "meta" : "control", "shift"]);
+ await check("existing Mod+Shift+V shortcut ends the connected call",
+ `s.counts.end === 1 && !s.snapshot.stopping && s.snapshot.call?.phase === 'ended' && ${button("Live voice")}`);
+ await clean();
+}
+
+async function playbackScenario() {
+ await fresh();
+ await evaluate("window.liveVoiceFixture.blockPlayback(true)");
+ await start();
+ await connected();
+ await check("blocked output exposes Resume sound with details closed",
+ `s.snapshot.call.playbackBlocked && ${button("Resume sound")} && ${noDialog}`);
+ await click(button("Resume sound"));
+ await check("failed playback retry is visible without opening details",
+ `s.snapshot.errorCode === 'LIVE_PLAYBACK_FAILED' && ui.all('[role=alert]').length > 0 && ${button("Resume sound")} && ${noDialog} && s.counts.play >= 2`);
+ await evaluate("window.liveVoiceFixture.blockPlayback(false)");
+ await click(button("Resume sound"));
+ await check("successful user retry clears playback blockage and error",
+ `!s.snapshot.call.playbackBlocked && !s.snapshot.errorCode && !${button("Resume sound")} && ${noDialog}`);
+ await click(button("End call", bar));
+ await wait("playback call ended", "!s.snapshot.stopping && s.snapshot.call?.phase === 'ended'");
+ await clean();
+}
+
+async function enableWork() {
+ await openPreparation();
+ await click(button("Connect a work session", prep));
+ await click(checkbox("Allow work requests"));
+}
+async function workScenario() {
+ await fresh();
+ await enableWork();
+ await check("work and context require separate opt-ins", `${checkbox("Allow work requests")}?.checked && ${checkbox("Share limited recent conversation context")}?.checked === false && ${noMedia}`);
+ await click(checkbox("Share limited recent conversation context"));
+ await click(`ui.named('select', 'Work session for the next call', ${JSON.stringify(prep)})`);
+ await key("End");
+ await key("Enter");
+ await check("changing selected work session clears context consent",
+ `ui.named('select', 'Work session for the next call', ${JSON.stringify(prep)})?.value === 'fixture-session-2' && ${checkbox("Share limited recent conversation context")}?.checked === false && ${noMedia}`);
+ await click(checkbox("Share limited recent conversation context"));
+ await click(checkbox("Allow work requests"));
+ await click(checkbox("Allow work requests"));
+ await check("removing work opt-in clears context consent", `${checkbox("Share limited recent conversation context")}?.checked === false && ${noMedia}`);
+ await click(checkbox("Share limited recent conversation context"));
+ await click(button("Close", prep));
+ await enableWork();
+ await check("reopening preparation does not retain context consent", `${checkbox("Share limited recent conversation context")}?.checked === false && ${noMedia}`);
+ await click(button("Start Live voice", prep));
+ await connected();
+ await check("only explicit work opt-in reaches prepare with selected target",
+ "s.requests.prepare[0].workTarget?.workSessionId === 'fixture-session-1' && s.requests.prepare[0].workTarget.contextEnabled === false && s.counts.audioContext === 1");
+ await click(button("End call", bar));
+ await wait("work call ended", `!s.snapshot.stopping && ${button("Live voice")}`);
+ await openPreparation();
+ await click(button("Connect a work session", prep));
+ await check("the next call resets work opt-in", `${checkbox("Allow work requests")}?.checked === false`);
+ await key("Escape");
+ await clean();
+}
+
+async function unconfirmedReleaseScenario() {
+ await fresh();
+ await enableWork();
+ await click(button("Start Live voice", prep));
+ await connected();
+ await evaluate("window.liveVoiceFixture.failReleaseReport(); window.liveVoiceFixture.beginClosing()");
+ await check("release failure keeps Ending until Main reports quarantine",
+ "s.snapshot.stopping && s.counts.released === 1 && s.contexts[0].state === 'closed' && ui.state('stopping')");
+ await evaluate("window.liveVoiceFixture.terminalUnconfirmed()");
+ await check("unconfirmed release stays visible and suppresses another Start",
+ `!s.snapshot.stopping && s.snapshot.call?.error?.code === 'LIVE_MEDIA_RELEASE_UNCONFIRMED' && ui.visible(document.querySelector('.live-voice-status-host')) && !${button("Live voice")} && !${button("Dismiss", bar)}`);
+ const attempt = await evaluate("window.liveVoiceFixture.attemptStart()");
+ assert.equal(attempt, "LIVE_MEDIA_RELEASE_UNCONFIRMED");
+ await check("Main quarantine cannot be cleared by retrying from the controller",
+ "s.counts.prepare === 1 && s.snapshot.call?.error?.code === 'LIVE_MEDIA_RELEASE_UNCONFIRMED'");
+ await clean();
+}
+
+async function shellAndDisableScenario() {
+ await fresh();
+ await enableWork();
+ await click(button("Start Live voice", prep));
+ await connected();
+ await click(button("Fixture toggle composer visibility"));
+ await check("global status survives the simulated hidden composer boundary",
+ "document.querySelector('[data-fixture-composer]')?.hidden && ui.state('connected') && ui.visible(document.querySelector('.live-voice-status-host'))");
+ await click(button("Fixture settings route"));
+ await check("global status survives simulated route unmount",
+ `!document.querySelector('[data-fixture-composer]') && ui.state('connected') && ${button("End call", bar)} && s.counts.end === 0`);
+ await click(button("Unmute microphone", bar));
+ await check("global call remains controllable away from composer", "!s.snapshot.call.muted && s.tracks[0].enabled");
+ await evaluate("window.liveVoiceFixture.hold('contextClose'); window.liveVoiceFixture.hold('released'); window.liveVoiceFixture.configure({ enabled: false }); window.liveVoiceFixture.beginClosing()");
+ await check("disable keeps stopping visible while AudioContext release is delayed",
+ "s.snapshot.status.enabled === false && s.snapshot.stopping && ui.state('stopping') && s.counts.contextClose === 1 && s.contexts[0].state !== 'closed'");
+ await evaluate("window.liveVoiceFixture.terminal()");
+ await check("terminal view before local release cannot hide Ending status",
+ "s.snapshot.call?.phase === 'ended' && s.snapshot.stopping && ui.state('stopping') && document.querySelector('.live-voice-call-bar').textContent.includes('Ending')");
+ await evaluate("window.liveVoiceFixture.release('contextClose')");
+ await check("release report acknowledgement also gates stopping",
+ "s.counts.released === 1 && s.contexts[0].state === 'closed' && s.snapshot.stopping && ui.state('stopping')");
+ await evaluate("window.liveVoiceFixture.release('released')");
+ await check("disabled status disappears only after local cleanup settles",
+ "!s.snapshot.stopping && !ui.visible(document.querySelector('.live-voice-status-host')) && s.tracks.every(track => track.readyState === 'ended')");
+ await click(button("Fixture chat route"));
+ await check("returning to composer while disabled leaves no Live or work icons",
+ "ui.all('button', undefined, '[data-fixture-composer]').length === 0 && s.counts.prepare === 1 && s.counts.getUserMedia === 1");
+ await clean();
+}
+
+app.whenReady().then(async () => {
+ win = new BrowserWindow({ show: false, width: 1120, height: 840, useContentSize: true,
+ webPreferences: { sandbox: true, nodeIntegration: false, contextIsolation: true, backgroundThrottling: false } });
+ win.removeMenu();
+ win.webContents.setWindowOpenHandler(() => ({ action: "deny" }));
+ win.webContents.session.setPermissionRequestHandler((_contents, _permission, callback) => { permissionRequests += 1; callback(false); });
+ win.webContents.session.setPermissionCheckHandler(() => false);
+ const origin = new URL(process.env.PI_LIVE_VOICE_FIXTURE_URL).origin;
+ win.webContents.session.webRequest.onBeforeRequest((request, callback) => {
+ const allowed = new URL(request.url).origin === origin || /^(data|blob):/.test(request.url);
+ if (!allowed) deniedRequests.push(request.url);
+ callback({ cancel: !allowed });
+ });
+ for (const scenario of [preparationScenario, cancellationScenario, connectedScenario, playbackScenario, workScenario, shellAndDisableScenario, unconfirmedReleaseScenario]) {
+ console.log(`SCENARIO ${scenario.name}`);
+ await scenario();
+ }
+ assert.equal(permissionRequests, 0, "Fixture must never request real microphone permission");
+ assert.deepEqual(deniedRequests, [], "Fixture must never attempt external network access");
+ writeFileSync(artifact("results.json"), JSON.stringify({
+ scope: "Mounted production controls/controller/store/i18n with simulated shell visibility and fake external edges; not full AppShell or provider/device E2E",
+ results, permissionRequests, deniedRequests,
+ }, null, 2));
+ console.log(`SUMMARY ${results.length}/${results.length} passed`);
+ win.destroy(); app.exit(0);
+}).catch(async (error) => {
+ console.error(error.stack);
+ results.push({ name: "scenario aborted", ok: false, error: String(error.stack ?? error) });
+ writeFileSync(artifact("results.json"), JSON.stringify({ results, permissionRequests, deniedRequests }, null, 2));
+ if (win && !win.isDestroyed()) {
+ try { writeFileSync(artifact("failure.png"), (await win.webContents.capturePage()).toPNG()); }
+ catch (captureError) { console.error("Failure screenshot unavailable", captureError); }
+ win.destroy();
+ }
+ app.exit(1);
+});
diff --git a/apps/desktop/test/fixtures/live-voice-interaction.jsx b/apps/desktop/test/fixtures/live-voice-interaction.jsx
new file mode 100644
index 000000000..2f308613e
--- /dev/null
+++ b/apps/desktop/test/fixtures/live-voice-interaction.jsx
@@ -0,0 +1,292 @@
+import React, { useEffect, useState } from "react";
+import { createRoot } from "react-dom/client";
+import i18n from "i18next";
+import { initReactI18next } from "react-i18next";
+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";
+import { IPC, KEYBOARD_SHORTCUTS, keybindingMatchesEvent, resolveKeybinding } from "@pi-desktop/shared";
+import { useAppStore } from "../../src/stores/app-store";
+import { PortalVisibilityProvider } from "../../src/lib/portal-visibility";
+import { LiveVoiceControls } from "../../src/features/voice/live/LiveVoiceControls";
+import { LiveVoiceStatusHost } from "../../src/features/voice/live/LiveVoiceStatusHost";
+import { getLiveCallController } from "../../src/features/voice/live/live-call-controller";
+import { runLiveVoiceShortcut } from "../../src/features/voice/live/live-voice-shortcuts";
+
+// Only external IPC/provider/media edges are fake. No controller or UI method is replaced.
+const listeners = new Map();
+const gates = new Map();
+const counts = Object.fromEntries([
+ "prepare", "connect", "getUserMedia", "audioContext", "end", "released", "contextClose",
+ "play", "pause", "mute", "peer", "trackStop",
+].map((key) => [key, 0]));
+const requests = { prepare: [], mute: [], end: [], unexpected: [] };
+const errors = [];
+const tracks = [];
+const contexts = [];
+const peers = [];
+const settings = {
+ liveVoice: { enabled: false, selectedBindingId: "fixture-selected", bindings: [
+ { id: "fixture-selected", adapterId: "codex-live", providerId: "fixture-provider", voice: "cove" },
+ { id: "fixture-other", adapterId: "codex-live", providerId: "fixture-other-provider", voice: "cove" },
+ ] },
+ voice: { deviceId: null }, keybindings: {},
+};
+const status = {
+ enabled: false, settingsRevision: 1, selectedBindingId: "fixture-selected", call: null,
+ bindings: [
+ { bindingId: "fixture-selected", adapterId: "codex-live", providerLabel: "Selected fixture account", configured: true, credentialsPresent: true, selectable: true },
+ { bindingId: "fixture-other", adapterId: "codex-live", providerLabel: "Other ready account", configured: true, credentialsPresent: true, selectable: true },
+ ],
+};
+const sessions = ["Alpha", "Beta"].map((title, index) => ({
+ id: `fixture-session-${index + 1}`, title, source: "desktop", projectPath: "/fixture/project",
+ createdAt: "2026-01-01T00:00:00Z", updatedAt: "2026-01-01T00:00:00Z", messageCount: 0,
+}));
+let call;
+let callNumber = 0;
+let rejectPlayback = false;
+let rejectReleaseReport = false;
+const ending = new Map();
+const emit = (channel, value) => {
+ for (const listener of listeners.get(channel) ?? []) listener(structuredClone(value));
+};
+const waitAt = (name) => gates.get(name)?.promise ?? Promise.resolve();
+function updateCall(patch) {
+ call = { ...call, ...patch, revision: (call?.revision ?? 0) + 1 };
+ status.call = call;
+ emit(IPC.event.liveVoiceChanged, call);
+ return structuredClone(call);
+}
+function beginClosing() {
+ if (!call || ["closing", "ended", "failed"].includes(call.phase)) return;
+ updateCall({ phase: "closing" });
+ emit(IPC.event.liveVoiceControl, { callId: call.callId, kind: "release-media" });
+}
+async function handleInvoke(channel, request) {
+ switch (channel) {
+ case IPC.invoke.settingsGet: return structuredClone(settings);
+ case IPC.invoke.liveVoiceStatus: return structuredClone(status);
+ case IPC.invoke.liveVoicePrepare: {
+ counts.prepare += 1;
+ requests.prepare.push(structuredClone(request));
+ call = {
+ callId: `fixture-call-${++callNumber}`, revision: 0, bindingId: request.bindingId,
+ adapterId: "codex-live", phase: "preparing", muted: request.initialMuted,
+ microphoneActive: false, userSpeaking: false, assistantSpeaking: false, mediaRelease: "pending",
+ ...(request.workTarget ? { workBinding: {
+ ...request.workTarget, workBindingRevision: 1,
+ label: sessions.find((session) => session.id === request.workTarget.workSessionId)?.title ?? "Fixture session",
+ } } : {}),
+ };
+ updateCall({});
+ const prepared = {
+ callId: call.callId, requestId: request.requestId, bindingId: call.bindingId,
+ adapterId: call.adapterId, mediaKind: "webrtc", initialMuted: request.initialMuted,
+ inputSampleRate: 24000, outputSampleRate: 24000, revision: call.revision,
+ };
+ await waitAt("prepare");
+ return prepared;
+ }
+ case IPC.invoke.liveVoiceConnect:
+ counts.connect += 1;
+ await waitAt("connect");
+ return { answerSdp: "v=0\r\n", revision: call.revision };
+ case IPC.invoke.liveVoiceSetMuted:
+ counts.mute += 1;
+ requests.mute.push(structuredClone(request));
+ return updateCall({ muted: request.muted });
+ case IPC.invoke.liveVoiceReportMedia:
+ if (request.kind === "released") {
+ counts.released += 1;
+ await waitAt("released");
+ if (rejectReleaseReport) throw Object.assign(new Error("Fixture release acknowledgement refused"), { code: "LIVE_MEDIA_RELEASE_UNCONFIRMED" });
+ return updateCall({ microphoneActive: false, mediaRelease: "confirmed" });
+ }
+ if (request.kind === "microphone-active") return updateCall({ microphoneActive: request.active });
+ if (request.kind === "phase") return updateCall({ phase: request.phase });
+ if (request.kind === "playback-blocked") return updateCall({ playbackBlocked: request.blocked });
+ return structuredClone(call);
+ case IPC.invoke.liveVoiceEnd: {
+ counts.end += 1;
+ requests.end.push(structuredClone(request));
+ const key = request.callId ?? request.requestId;
+ if (!ending.has(key)) ending.set(key, (async () => {
+ beginClosing();
+ await waitAt("end");
+ if (call) updateCall({ phase: "ended" });
+ return { ok: true };
+ })());
+ return ending.get(key);
+ }
+ case IPC.invoke.liveVoiceHeartbeat:
+ case IPC.invoke.liveVoiceReportPlayback:
+ case IPC.invoke.liveVoiceReportControlApplied:
+ return { ok: true };
+ default:
+ requests.unexpected.push(channel);
+ throw new Error(`Unexpected fixture IPC: ${channel}`);
+ }
+}
+window.piDesktop = {
+ platform: navigator.platform.includes("Mac") ? "darwin" : "linux",
+ on(channel, listener) {
+ const group = listeners.get(channel) ?? new Set();
+ listeners.set(channel, group); group.add(listener);
+ return () => group.delete(listener);
+ },
+ onLiveVoicePort: () => () => {},
+ async invoke(channel, request) { return { ok: true, data: await handleInvoke(channel, request) }; },
+};
+Object.defineProperty(navigator, "mediaDevices", { configurable: true, value: {
+ async getUserMedia() {
+ counts.getUserMedia += 1;
+ const track = { enabled: true, readyState: "live", stop() {
+ if (this.readyState !== "ended") counts.trackStop += 1;
+ this.readyState = "ended"; this.enabled = false;
+ } };
+ tracks.push(track);
+ await waitAt("microphone");
+ return { getTracks: () => [track], getAudioTracks: () => [track] };
+ },
+} });
+class FakePeer extends EventTarget {
+ connectionState = "new";
+ iceGatheringState = "complete";
+ localDescription = null;
+ channel = Object.assign(new EventTarget(), {
+ readyState: "open", send() {}, close() { this.readyState = "closed"; },
+ });
+ constructor() { super(); counts.peer += 1; peers.push(this); }
+ createDataChannel() { return this.channel; }
+ addTrack() {}
+ async createOffer() { return { type: "offer", sdp: "v=0\r\n" }; }
+ async setLocalDescription(description) { this.localDescription = description; }
+ async setRemoteDescription() {
+ if (this.connectionState === "closed") throw new DOMException("Fixture peer is closed", "InvalidStateError");
+ this.connectionState = "connected";
+ this.dispatchEvent(new Event("connectionstatechange"));
+ this.ontrack?.({ streams: [{}] });
+ }
+ close() { this.connectionState = "closed"; this.dispatchEvent(new Event("connectionstatechange")); }
+}
+window.RTCPeerConnection = FakePeer;
+class FakeAudioContext {
+ state = "running";
+ sampleRate = 48000;
+ destination = {};
+ constructor() { counts.audioContext += 1; contexts.push(this); }
+ async resume() { this.state = "running"; }
+ async close() { counts.contextClose += 1; await waitAt("contextClose"); this.state = "closed"; }
+ createMediaElementSource() { return { connect() {}, disconnect() {} }; }
+ createAnalyser() { return { fftSize: 1024, connect() {}, disconnect() {}, getFloatTimeDomainData(samples) { samples.fill(0); } }; }
+ createGain() { return { gain: { value: 1 }, connect() {}, disconnect() {} }; }
+}
+window.AudioContext = FakeAudioContext;
+const mediaSources = new WeakMap();
+Object.defineProperty(HTMLMediaElement.prototype, "srcObject", {
+ configurable: true, get() { return mediaSources.get(this) ?? null; }, set(value) { mediaSources.set(this, value); },
+});
+HTMLMediaElement.prototype.play = async function () {
+ counts.play += 1;
+ if (rejectPlayback) throw Object.assign(new Error("Fixture playback blocked"), { code: "LIVE_PLAYBACK_FAILED" });
+};
+HTMLMediaElement.prototype.pause = function () { counts.pause += 1; };
+window.addEventListener("error", (event) => errors.push(event.message));
+window.addEventListener("unhandledrejection", (event) => errors.push(String(event.reason)));
+
+await i18n.use(initReactI18next).init({
+ lng: "en", fallbackLng: "en", keySeparator: false,
+ resources: { en: { translation: flattenCatalog(catalogs.en) } }, interpolation: { escapeValue: false },
+});
+useAppStore.setState({ sessions, activeSessionId: sessions[0].id, settings });
+const controller = getLiveCallController();
+function SimulatedShell() {
+ const [route, setRoute] = useState("chat");
+ const [hidden, setHidden] = useState(false);
+ const activeSessionId = useAppStore((state) => state.activeSessionId);
+ useEffect(() => {
+ useAppStore.setState({ page: route });
+ }, [route]);
+ useEffect(() => {
+ // Production matcher + dispatcher, not the unrelated full AppShell runtime.
+ const onKeyDown = (event) => {
+ if (event.repeat || event.defaultPrevented) return;
+ const platform = window.piDesktop.platform;
+ const shortcut = KEYBOARD_SHORTCUTS.find((item) => ["voiceToggle", "voiceCancel"].includes(item.id)
+ && keybindingMatchesEvent(resolveKeybinding(item, settings.keybindings, platform), event, platform));
+ if (shortcut && runLiveVoiceShortcut(shortcut.id)) event.preventDefault();
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, []);
+ return (
+ <div style={{ minHeight: "100vh", padding: 32 }}>
+ <nav aria-label="Fixture shell navigation" style={{ display: "flex", gap: 16 }}>
+ <button onClick={() => setRoute("settings")}>Fixture settings route</button>
+ <button onClick={() => { setRoute("chat"); setHidden(false); }}>Fixture chat route</button>
+ <button onClick={() => setHidden((value) => !value)}>Fixture toggle composer visibility</button>
+ <button onClick={() => useAppStore.setState({ activeSessionId: sessions[1].id })}>Fixture switch session</button>
+ </nav>
+ <main><p>Simulated shell boundary, not a mounted AppShell.</p></main>
+ {route === "chat" ? (
+ <PortalVisibilityProvider visible={!hidden}>
+ <div data-fixture-composer hidden={hidden} style={{ position: "absolute", bottom: 72, left: 64 }}>
+ <LiveVoiceControls t={i18n.t.bind(i18n)} workSessionId={activeSessionId} workSessionLabel="Fixture project / Alpha" />
+ </div>
+ </PortalVisibilityProvider>
+ ) : <p data-fixture-settings>Settings route: composer unmounted</p>}
+ <LiveVoiceStatusHost />
+ </div>
+ );
+}
+createRoot(document.getElementById("root")).render(<SimulatedShell />);
+window.liveVoiceFixture = {
+ hold(name) {
+ if (gates.has(name)) throw new Error(`Gate already held: ${name}`);
+ let resolve;
+ const promise = new Promise((done) => { resolve = done; });
+ gates.set(name, { promise, resolve });
+ },
+ release(name) {
+ const gate = gates.get(name);
+ if (!gate) throw new Error(`Gate not held: ${name}`);
+ gates.delete(name); gate.resolve();
+ },
+ async configure(patch) {
+ if (patch.enabled !== undefined) status.enabled = settings.liveVoice.enabled = patch.enabled;
+ if (patch.selectedAvailable !== undefined) {
+ status.bindings[0].selectable = patch.selectedAvailable;
+ status.bindings[0].credentialsPresent = patch.selectedAvailable;
+ status.bindings[0].reason = patch.selectedAvailable ? undefined : "missing-credentials";
+ }
+ status.settingsRevision += 1;
+ emit(IPC.event.settingsChanged, { liveVoice: settings.liveVoice });
+ await controller.refreshStatus();
+ },
+ blockPlayback(blocked) { rejectPlayback = blocked; },
+ beginClosing,
+ setPhase(phase) { updateCall({ phase }); },
+ switchSession(sessionId) { useAppStore.setState({ activeSessionId: sessionId }); },
+ failReleaseReport() { rejectReleaseReport = true; },
+ terminal() { updateCall({ phase: "ended" }); },
+ terminalUnconfirmed() {
+ updateCall({ phase: "failed", mediaRelease: "unconfirmed", error: {
+ code: "LIVE_MEDIA_RELEASE_UNCONFIRMED", stage: "cleanup", retriable: false,
+ } });
+ },
+ async attemptStart() {
+ try { await controller.start(); return null; }
+ catch (error) { return error && typeof error === "object" && "code" in error ? error.code : "unknown"; }
+ },
+ transcript(text) {
+ emit(IPC.event.liveVoiceTranscript, { callId: call.callId,
+ segment: { id: "fixture-transcript", role: "assistant", text, final: true, timestamp: 0 } });
+ },
+ inspect() {
+ return {
+ snapshot: controller.getSnapshot(), counts, requests, errors,
+ tracks: tracks.map(({ enabled, readyState }) => ({ enabled, readyState })),
+ contexts: contexts.map(({ state }) => ({ state })),
+ peers: peers.map(({ connectionState }) => ({ connectionState })), held: [...gates.keys()],
+ };
+ },
+};
diff --git a/apps/desktop/test/live-voice-controller.test.mjs b/apps/desktop/test/live-voice-controller.test.mjs
index 8019929cb..95703ee4e 100644
--- a/apps/desktop/test/live-voice-controller.test.mjs
+++ b/apps/desktop/test/live-voice-controller.test.mjs
@@ -169,6 +169,7 @@ test("renderer and Main complete a Codex Live user path without invoking an Agen
await controller.end();
assert.equal(controller.getSnapshot().call.phase, "ended");
+ assert.equal(controller.getSnapshot().stopping, false);
assert.equal(tracks[0].stopped, true);
assert.equal(sentViews.at(-1).phase, "ended");
assert.equal(controller.getSnapshot().transcripts.length, 1);
diff --git a/apps/desktop/test/live-voice-controls.test.mjs b/apps/desktop/test/live-voice-controls.test.mjs
index 797d948eb..bc2e8e155 100644
--- a/apps/desktop/test/live-voice-controls.test.mjs
+++ b/apps/desktop/test/live-voice-controls.test.mjs
@@ -3,8 +3,15 @@ import test from "node:test";
import { fileURLToPath } from "node:url";
import { createServer } from "vite";
-test("Live Voice remains reachable while disabled and exposes toggle state accessibly", async (t) => {
+const binding = { bindingId: "voice-a", adapterId: "codex-live", configured: true, credentialsPresent: true, selectable: true, providerLabel: "Fixture voice" };
+const status = { enabled: true, settingsRevision: 1, selectedBindingId: binding.bindingId, bindings: [binding], call: null };
+const call = { callId: "call-a", revision: 1, bindingId: binding.bindingId, adapterId: binding.adapterId, phase: "connected", muted: true, microphoneActive: true, userSpeaking: false, assistantSpeaking: false };
+const snapshot = { status, call: null, transcripts: [], starting: false, stopping: false };
+
+test("Live Voice separates idle entry and compact call presentation", async (t) => {
const originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
+ let currentStatus = { ...status, enabled: false };
+ const requests = [];
Object.defineProperty(globalThis, "window", {
configurable: true,
value: {
@@ -13,7 +20,12 @@ test("Live Voice remains reachable while disabled and exposes toggle state acces
removeEventListener() {},
piDesktop: {
on: () => () => undefined,
- invoke: async () => ({ ok: true, data: { voice: { enabled: false, languages: [] } } }),
+ invoke: async (channel) => {
+ requests.push(channel);
+ if (channel === "pi-desktop/voice/live/status") return { ok: true, data: currentStatus };
+ if (channel === "pi-desktop/settings/get") return { ok: true, data: {} };
+ throw new Error(`Unexpected IPC request: ${channel}`);
+ },
},
},
});
@@ -33,10 +45,84 @@ test("Live Voice remains reachable while disabled and exposes toggle state acces
const React = await import("react");
const { renderToStaticMarkup } = await import("react-dom/server");
const { LiveVoiceControls } = await server.ssrLoadModule("/src/features/voice/live/LiveVoiceControls.tsx");
- const html = renderToStaticMarkup(React.createElement(LiveVoiceControls, { t: (key) => key }));
+ const { LiveVoiceCallBar } = await server.ssrLoadModule("/src/features/voice/live/LiveVoiceCallBar.tsx");
+ const { getLiveCallController } = await server.ssrLoadModule("/src/features/voice/live/live-call-controller.ts");
+ const { liveVoiceMode, liveVoiceIssue, liveReadinessMessage, hasUnconfirmedMediaRelease } = await server.ssrLoadModule("/src/features/voice/live/live-voice-presentation.ts");
+ const translate = (key) => key;
+ const controller = getLiveCallController();
+ const renderEntry = () => renderToStaticMarkup(React.createElement(LiveVoiceControls, { t: translate, workSessionId: "work-a" }));
+ const renderBar = (next, issue = liveVoiceIssue(next)) => renderToStaticMarkup(React.createElement(LiveVoiceCallBar, {
+ t: translate, snapshot: next, issue, detailsOpen: false, detailsRef: { current: null }, actionPending: null,
+ onCancel() {}, onMute() {}, onEnd() {}, onDetails() {}, onResume() {}, onSettings() {}, onDismiss() {},
+ }));
+
+ await t.test("disabled hides both the voice and work entry", async () => {
+ await controller.refreshStatus();
+ assert.equal(renderEntry(), "");
+ });
+
+ await t.test("enabled idle exposes exactly one preparation trigger", async () => {
+ currentStatus = status;
+ await controller.refreshStatus();
+ const html = renderEntry();
+ assert.equal((html.match(/<button\b/g) ?? []).length, 1);
+ assert.match(html, /aria-label="liveVoice\.title"/);
+ assert.match(html, /aria-expanded="false"/);
+ assert.match(html, /aria-haspopup="dialog"/);
+ assert.doesNotMatch(html, /role="dialog"|liveVoice\.openWorkSetup/);
+ assert.ok(requests.every((channel) => channel.endsWith("/status") || channel.endsWith("/get")));
+ });
+
+ await t.test("readiness belongs to the selected binding, not any available account", () => {
+ assert.equal(liveReadinessMessage(status), null);
+ assert.equal(liveReadinessMessage({ ...status, selectedBindingId: "missing" }), "liveVoice.noProvider");
+ assert.equal(liveReadinessMessage({ ...status, bindings: [{ ...binding, selectable: false, reason: "missing-credentials" }, { ...binding, bindingId: "other" }] }), "liveVoice.readiness.missing-credentials");
+ });
+
+ await t.test("cleanup wins over terminal views and disabled settings", () => {
+ assert.equal(liveVoiceMode({ ...snapshot, starting: true }), "connecting");
+ assert.equal(liveVoiceMode({ ...snapshot, call }), "connected");
+ const reconnecting = { ...snapshot, call: { ...call, phase: "reconnecting" } };
+ assert.equal(liveVoiceMode(reconnecting), "reconnecting");
+ const reconnectingHtml = renderBar(reconnecting);
+ assert.match(reconnectingHtml, /liveVoice\.phase\.reconnecting/);
+ assert.match(reconnectingHtml, /aria-label="liveVoice\.end"/);
+ assert.doesNotMatch(reconnectingHtml, /aria-label="common\.cancel"|aria-label="liveVoice\.unmute"/);
+ const closing = { ...snapshot, status: { ...status, enabled: false }, call: { ...call, phase: "ended" }, stopping: true };
+ assert.equal(liveVoiceMode(closing), "stopping");
+ const html = renderBar(closing);
+ assert.match(html, /data-state="stopping"/);
+ assert.match(html, /role="status"/);
+ assert.match(html, /liveVoice\.phase\.closing/);
+ assert.doesNotMatch(html, /<button\b/);
+ assert.equal(liveVoiceMode({ ...closing, stopping: false }), "idle");
+ });
- assert.match(html, /aria-label="liveVoice\.start"/);
- assert.match(html, /aria-pressed="false"/);
- assert.match(html, /aria-haspopup="dialog"/);
- assert.doesNotMatch(html, /<button[^>]*disabled(?:="")?/);
+ await t.test("connected mute, end and details stay directly reachable", () => {
+ const html = renderBar({ ...snapshot, call });
+ assert.match(html, /liveVoice\.muted/);
+ for (const key of ["unmute", "end", "details"]) assert.match(html, new RegExp(`aria-label="liveVoice\\.${key}"`));
+ assert.doesNotMatch(html, /role="dialog"/);
+ });
+
+ await t.test("playback recovery and Main errors are visible without details", () => {
+ const blocked = { ...snapshot, call: { ...call, playbackBlocked: true } };
+ assert.match(renderBar(blocked), /aria-label="liveVoice\.resumePlayback"/);
+ assert.match(renderBar(blocked), /liveVoice\.playbackBlocked/);
+ const failure = { ...snapshot, call: { ...call, phase: "failed", error: { code: "LIVE_MEDIA_RELEASE_UNCONFIRMED", retriable: false } } };
+ const failureHtml = renderBar(failure);
+ assert.match(failureHtml, /role="alert"/);
+ assert.match(failureHtml, /liveVoice\.mediaReleaseUnconfirmed/);
+ assert.doesNotMatch(failureHtml, /aria-label="errors\.action\.dismiss"/);
+ const quarantined = liveVoiceIssue({
+ ...snapshot,
+ call: { ...call, phase: "failed", error: { code: "LIVE_CALL_ACTION_FAILED", retriable: false } },
+ errorCode: "LIVE_MEDIA_RELEASE_UNCONFIRMED",
+ });
+ assert.equal(quarantined.code, "LIVE_MEDIA_RELEASE_UNCONFIRMED");
+ assert.equal(quarantined.message, "liveVoice.mediaReleaseUnconfirmed");
+ assert.equal(hasUnconfirmedMediaRelease({ ...snapshot, errorCode: "LIVE_MEDIA_RELEASE_UNCONFIRMED" }), true);
+ assert.equal(liveVoiceIssue({ ...snapshot, call: { ...call, playbackBlocked: false, notice: { code: "LIVE_PLAYBACK_BLOCKED", retriable: true } } }), null);
+ assert.equal(liveVoiceIssue({ ...snapshot, call: { ...call, notice: { code: "LIVE_EXECUTION_NOT_CONNECTED", retriable: false } } }).message, "liveVoice.workNotConnected");
+ });
});
diff --git a/docs/spec/03-runtime/live-voice.md b/docs/spec/03-runtime/live-voice.md
index 353822066..3ce820858 100644
--- a/docs/spec/03-runtime/live-voice.md
+++ b/docs/spec/03-runtime/live-voice.md
@@ -48,6 +48,51 @@ suspend/lock, provider change, disable and app quit stop media and close the
adapter. If renderer media release is not confirmed, Main quarantines the
microphone lease instead of reusing it blindly.
+## Interaction states
+
+Live Voice uses four presentation states without changing the call protocol or
+persisted settings:
+
+1. **Disabled:** no Live Voice or Live Work icon appears in the Composer. The
+ only enablement entry is Settings → Voice, subject to its existing developer
+ mode and development-build gates. Enabling the feature does not start a call.
+2. **Enabled and idle:** one Live Voice icon opens a compact preparation surface.
+ Opening, closing, or expanding it never invokes prepare, requests microphone
+ access, creates media resources, or contacts a voice provider. It identifies
+ the exact selected binding and its readiness reason; another ready binding
+ does not make an unavailable selected binding usable. Start is explicit and
+ starts muted. Optional work access is collapsed initially and requires its
+ own opt-in plus a valid local target; expanding it is not authorization.
+3. **Call in progress:** a stable global compact bar shows startup with Cancel,
+ connected state with mute/unmute, End and Details, and stopping with an
+ explicit Ending state. It is mounted in persistent AppShell chrome outside
+ the visibility-gated chat and Composer subtree, so in-app navigation cannot
+ hide the call controls.
+ Playback blocking and errors, including playback-resume failure, are visible
+ directly in the bar instead of requiring Details. Non-terminal action or
+ missing-work-binding warnings do not falsely say the call has stopped.
+4. **Details open:** an explicitly opened secondary surface contains the
+ transient transcript, provider identity, and any scoped work actions and
+ results. Startup and connection never open it automatically. Close, outside
+ press and Escape dismiss only this surface, not the call, and return focus
+ to an available trigger. The compact bar remains the call-control surface.
+
+Cancel, End, feature disable, and automatic termination retain the stopping bar
+until both Main termination and renderer media cleanup have settled. A Main
+terminal event alone is not proof that local media has been released. An
+unconfirmed release remains an observable error, suppresses another Start
+until the app is restarted, and stays visible because Main has quarantined the
+microphone lease. Hiding or dismissing the UI cannot clear that quarantine.
+Turning the feature off removes idle entry points, not pending cleanup
+visibility. In-app page/session navigation is distinct from renderer
+navigation or loss, which keeps its existing termination policy.
+
+The configurable Live Voice toggle shortcut deliberately starts a voice-only
+call directly from idle and ends an active call, preserving the existing
+shortcut contract. It does not inherit a preparation surface's work choice.
+The startup-cancel shortcut (Escape by default) cancels startup only if an open
+popup has not consumed that key. Escape never ends a connected call.
+
## Calls and media
The call state is `preparing → acquiring-mic → negotiating/connecting →
@@ -70,8 +115,8 @@ PCM capture uses an AudioWorklet with the actual `AudioContext.sampleRate`, a
stateful anti-aliasing resampler and bounded 20 ms worklet frames. PCM output is
queued in a separate playback path with per-item played cursors; interruption
advances a playback epoch and drops stale queued audio. If browser playback is
-blocked, the call panel offers a user gesture to resume it. Input never loops
-back to local speakers.
+blocked, the compact call bar offers a user gesture to resume it and reports
+resume failure there. Input never loops back to local speakers.
Mute, barge-in and end are distinct actions. Mute gates only new input and
keeps provider output available. Codex uses its provider-native full-duplex
diff --git a/docs/spec/03-runtime/live-work-session.md b/docs/spec/03-runtime/live-work-session.md
index 2edf92654..6c14e80af 100644
--- a/docs/spec/03-runtime/live-work-session.md
+++ b/docs/spec/03-runtime/live-work-session.md
@@ -14,17 +14,25 @@ subagent work under the session's current model and permission policy.
## Scope and authorization
- A call without a `workTarget` remains a voice-only call.
-- Enabling work access is an explicit renderer action. Main resolves the
- selected local session and creates a call-scoped `LiveWorkBinding`; a provider
- tool request cannot choose a session, project path, model, mode, or permission.
+- Enabling work access is an explicit renderer action, independent of opening
+ or expanding the preparation surface. A collapsed **Connect a work session**
+ section starts with **Allow work requests** unchecked. Start includes a
+ `workTarget` only after that opt-in and a valid local-session selection; an
+ expanded section, an existing session, or context consent alone never grants
+ work access. Main resolves the selected local session and creates a
+ call-scoped `LiveWorkBinding`; a provider tool request cannot choose a
+ session, project path, model, mode, or permission.
- A call's work binding does not follow sidebar selection. Opening another
session is navigation only; changing the work target requires a new call.
- The first implementation accepts local desktop sessions. Native Pi and
remote work sessions stay unavailable until their Host surfaces implement the
same scoped controls and terminal events.
-- Context sharing is an explicit work-call option. When disabled, the intent
- classifier receives the current request and bounded work-state metadata but
- does not read prior session messages.
+- Context sharing is a separate, unchecked-by-default, next-call work option.
+ Closing or reopening preparation, changing or creating the target session,
+ disabling work access, and finishing or canceling the call reset consent.
+ When disabled, the intent classifier receives the current request and bounded
+ work-state metadata but does not read prior session messages. No work or
+ context opt-in is persisted by this interaction.
## Candidate and routing flow
@@ -111,13 +119,29 @@ does not imply tests passed.
## UI and current capability boundary
-The existing Live panel displays the fixed work target, whether bounded context
-sharing is enabled, current operation admission/execution state, feedback
-delivery status, bounded route or rejection messages, exact terminal
-summaries, and short-lived project/session choices. It provides actions to view
-the bound session, open a listed session, create a session in a listed project,
-stop its observed running turn, or cancel its exact queued item. Creating a
-session uses the existing defaults and leaves the current Live binding alone.
+Idle Composer uses the single Live Voice entry and its side-effect-free
+preparation surface; there is no second Live Work icon. A missing or ineligible
+target explains how to choose or create a local work session. The same explicit
+Start action starts a muted voice-only or opted-in work call. Opening the work
+section does not start a call, create a session, read conversation context, or
+authorize work.
+
+Call Details, opened deliberately from the global compact bar, displays the
+fixed work target, whether bounded context sharing is enabled, current operation
+admission/execution state, feedback delivery status, bounded route or rejection
+messages, exact terminal summaries, and short-lived project/session choices.
+It provides actions to view the bound session, open a listed session, create a
+session in a listed project, stop its observed running turn, or cancel its exact
+queued item. Creating a session uses the existing defaults and leaves the
+current Live binding alone. Closing Details, pressing outside it, or pressing
+Escape changes neither the call nor accepted work. Navigating to another page
+or session does not hide the global bar or retarget the work binding.
+
+The compact bar owns Cancel during startup and End/mute during the call;
+Ending remains visible through both Main and renderer cleanup even after the
+feature is disabled. End remains distinct from stopping an observed task or
+canceling an exact queue item. This presentation redesign changes no IPC,
+persistence, Host admission, permission, or context-projection contract.
### Work feedback and announcement policy
diff --git a/docs/spec/04-ux/06-settings-ia.md b/docs/spec/04-ux/06-settings-ia.md
index fb76f9d1c..a633fd109 100644
--- a/docs/spec/04-ux/06-settings-ia.md
+++ b/docs/spec/04-ux/06-settings-ia.md
@@ -70,6 +70,11 @@ Settings is a **full-window page** that replaces the app sidebar + main chrome (
lines are rendered. These are visual landmarks only, not a second navigation
level.
When search filters the directory, empty clusters and their headings disappear.
+- **Voice** is an Experimental Preferences destination between AI and
+ Shortcuts, present only in development builds while developer mode is on.
+ Its existing build/developer gate applies to the rail, page, search hits,
+ and idle Composer entry; this interaction redesign does not widen access.
+ It is the only place to enable Live Voice. See the Voice section below.
- **Cloud sync / 云同步** is a developer-only, Experimental destination: its
rail row, page, and settings-search hits exist only while
`AppSettings.developerMode` is `true`. With developer mode off the row is
@@ -294,6 +299,32 @@ The user-facing dashboard is marketplace plugin `pi.token-insights`, opened from
the command palette (`usage`, `tokens`, `用量`). Settings search does not index
a usage tab.
+### Voice (experimental)
+
+- This development-build and developer-mode gated destination owns Live Voice
+ enablement and provider bindings. Disabled Live Voice has no Composer voice
+ or work icon; enabling it reveals one preparation entry, never auto-starts a
+ call, and never grants work access.
+- Bind an existing compatible provider account, choose the exact next-call
+ binding, and configure its model, voice, and explicit Realtime profile where
+ applicable. Readiness describes that selected binding, not whether any other
+ configured provider is ready. Credentials remain in the existing Host/Main
+ systems and are not shown or copied into the renderer.
+- Provider-binding edits remain locked while that binding is active. Turning
+ Live Voice off ends the call, but the global compact call bar remains visible
+ through Main termination and renderer media cleanup, including while Settings
+ replaces the chat shell. An unconfirmed release keeps its error visible and
+ suppresses another Start until the app is restarted.
+- Work authorization belongs to an explicit opt-in and target in next-call
+ preparation, not to the Settings enable switch. Context sharing is a separate
+ unchecked, transient next-call choice. Settings copy distinguishes the
+ default voice-only call from explicitly authorized work requests.
+- Legacy Dictation and Host Speech settings remain hidden and their stored
+ values retain their meaning. No new persisted preference, IPC, provider
+ fallback, or permission rule is introduced. See
+ [Live Voice](../03-runtime/live-voice.md) and
+ [Live Work](../03-runtime/live-work-session.md).
+
### Shortcuts (`shortcuts` tab)
- **Keyboard shortcuts** card:
- lists navigation, agent, and window actions from one shared shortcut map
@@ -778,7 +809,9 @@ system while preserving their different data ownership:
Shortcuts / 快捷键, Instructions / 指令, Models / 模型, Skills / 技能, MCP,
Subagents / 子智能体, Import / 导入, Projects / 项目, Cloud sync / 云同步,
Remote Hosts / 远程主机, and Info / 信息 in that order. Cloud sync / 云同步
- and Remote Hosts / 远程主机 appear only while developer mode is on. The rows are grouped under Preferences / 偏好,
+ and Remote Hosts / 远程主机 appear only while developer mode is on. Voice
+ appears between AI and Shortcuts only in development builds with developer
+ mode on. The rows are grouped under Preferences / 偏好,
Agent / 智能体, Workspace / 工作区, and System / 系统. There is no
Usage / 用量 destination.
3. Appearance is part of General and has no standalone rail destination
diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.md
index 212ae21b1..a7fd9378c 100644
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@ -3155,7 +3155,55 @@ reasoning-level control.
unknown/custom models without an explicit override, disabled image input, and
oversized images use the existing canonical `@<path>` file-tool fallback.
There are no visual previews in MVP.
-- No voice input
+- No voice-to-draft input. The opt-in Live Voice path below is separate from
+ the Composer draft and does not restore the hidden Dictation entry.
+
+### 11.7.1 Live Voice preparation, compact call bar, and details
+
+Subject to the existing developer-mode and development-build gate, Live Voice
+has four presentation states:
+
+| State | Surface and allowed interaction |
+|---|---|
+| Disabled | No Live Voice or Live Work Composer icons. Enable only in Settings → Voice. |
+| Enabled, idle | One Live Voice icon opens preparation, not a call. Show the exact selected provider and readiness cause, an explicit Start action, and initially collapsed optional work controls. |
+| Call in progress | One global compact bar: Connecting with Cancel; connected with mute/unmute, End, and Details; Ending until Main and renderer cleanup both settle. |
+| Details open | Deliberately opened transcript/provider/work inspection surface; dismissing it does not end the call. |
+
+- The preparation popup uses shared controls and a localized accessible title.
+ Opening or dismissing it must not prepare a call, request microphone access,
+ initialize media, or contact a voice provider. Start is unavailable when the
+ exact selected binding is not ready, even if another binding is ready; show
+ the actual readiness cause and a Settings action instead of silently falling
+ back to another account.
+- Start defaults to muted. The work disclosure contains an independent,
+ unchecked **Allow work requests** opt-in, a valid local-session target, and
+ separate unchecked context consent. Expanding the section or selecting a
+ target is not authorization. A missing target offers choose/create guidance.
+ Context consent is next-call-only and resets on preparation dismissal,
+ reopening, target change/create, work opt-out, and call completion/cancel.
+- The compact bar is persistent AppShell chrome outside the visibility-gated
+ chat and Composer subtree. It stays available across Settings, Plugins, and
+ project/session navigation. Feature disable hides the idle icon but not the
+ stopping bar. Late Main terminal events and renderer media release cannot
+ briefly expose a second Start. Unconfirmed media release remains visible as
+ an error, suppresses another Start until restart, and cannot be cleared into a
+ reusable call slot by dismissing the presentation.
+- Playback paused state, Resume sound, playback-resume failure and call errors
+ are visible directly in the bar. Status is announced accessibly; icon-only
+ controls have localized names and tooltips, and muted state is explicit.
+- Details never opens automatically during startup or connection. It owns the
+ bounded transient transcript (including an empty state), provider identity,
+ fixed work binding, work actions and results. Close, outside press and Escape
+ dismiss the surface only and restore focus to an available trigger. The bar
+ remains usable, and dismissing Details never submits or stops work.
+- The configurable toggle shortcut retains deliberate direct voice-only start
+ from idle and end during a call. The startup-cancel shortcut only acts when
+ no popup has consumed the key; Escape never ends a connected call.
+
+See [Live Voice](../03-runtime/live-voice.md) and
+[Live Work](../03-runtime/live-work-session.md) for the unchanged ownership,
+permission, and call-scoped work contracts.
### 11.8 Slash commands, @ file references, and clipboard files (D123–D125, D197, D209, D262, D362, D397, ADR 0024, ADR 0059, ADR 0070, ADR 0131, ADR 0221, ADR 0222)
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 7f45cdf85..b5d0bf415 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -15,12 +15,14 @@
use a real provider account or paid endpoint for automation.
- **Steps:** Open Voice settings and confirm only Live Voice controls are
visible; legacy Dictation toggles, microphone selection and transcription
- model controls are absent. Confirm the Composer shows Live controls without
- the old Dictation microphone button. Bind/select a fixture account for each
- supported adapter profile. In Settings → Shortcuts, customize the Live Voice
- toggle and use it to start then end a fixture call. Cancel a pending startup
- with the `voiceCancel` binding (default `Escape`); pressing `Escape` during a
- connected call must not end it. Restore the default, then start, cancel during
+ model controls are absent. Confirm the enabled Composer shows one Live
+ preparation entry without a separate Work or old Dictation microphone button.
+ Bind/select a fixture account for each supported adapter profile. In Settings
+ → Shortcuts, customize the Live Voice toggle and use it to start then end a
+ fixture call. Cancel a pending startup
+ with the `voiceCancel` binding (default `Escape`) when no popup consumes the
+ key; pressing `Escape` during a connected call must not end it. Restore the
+ default, then explicitly Start from preparation, cancel during
permission/startup, connect, mute/unmute, interrupt playback, inspect the
in-memory transcript, and end. Repeat with Dictation already holding the
microphone, a changed active binding, a provider credential removal, renderer
@@ -43,6 +45,60 @@
The full Electron flow and real-provider/device compatibility remain
unverified until their respective isolated acceptance environments are run.
+### E2E-LIVE-VOICE-four-stage-ui
+
+- **Title:** Disabled, preparation, compact call, and deliberate details.
+- **Preconditions:** Isolated development-build Electron profile with developer
+ mode on, Live Voice initially disabled, deterministic local provider/media
+ fixtures, and local work-session fixtures. No real account, microphone,
+ speaker, paid endpoint, or user's running Desktop instance is used.
+- **Steps:**
+ 1. Confirm neither Live nor Work Composer icon exists while disabled. Enable
+ Live Voice only from Settings → Voice; verify exactly one idle voice icon.
+ 2. Open preparation and expand/collapse work options without starting. Verify
+ no prepare request, microphone acquisition, media initialization, provider
+ connection, or work dispatch occurs. Make the selected binding unavailable
+ while another is ready: show the exact selected identity/reason, disable
+ Start, and do not switch providers implicitly.
+ 3. With a ready binding, explicitly Start and observe Connecting plus Cancel
+ in the compact bar, without automatically opening Details. Cancel while
+ prepare or media acquisition is pending and deliver the late completion.
+ Repeat Start to connect muted, then unmute/mute and inspect status.
+ 4. Open Details, inspect transcript/provider/work state, and dismiss it with
+ Close, outside press, and Escape. Keep the call connected; use the bar to
+ resume blocked sound, observe a rejected resume, and recover explicitly.
+ 5. Navigate between chat, Settings, Plugins, and sessions. End or disable the
+ feature with delayed Main termination and renderer cleanup, in either
+ completion order. Keep Ending visible and prevent another Start until both
+ settle. Exercise unconfirmed release and verify visible blocked recovery.
+ 6. Reopen preparation: work access and context consent are unchecked. Merely
+ expanding the section or selecting a session never starts a call; Start
+ without the work opt-in is voice-only. Opt into work explicitly, select a
+ valid local target, and Start; inspect the fixed binding and work results
+ in Details. End and reopen preparation, then change/create the target,
+ opt out, or cancel and verify context consent resets. Ending Live does not
+ stop already accepted work.
+ 7. Use the configured toggle to start a voice-only call directly and end it.
+ During startup, a popup consumes Escape to dismiss itself without
+ cancellation; without a consuming popup, the startup-cancel shortcut works.
+ Escape never ends a connected call. Repeat visible controls in English and
+ Simplified Chinese and check catalog coverage for all shipped locales.
+- **Expected:** Four distinct UI states, deliberate startup and work consent,
+ exact-binding readiness, default mute, global cleanup visibility, accessible
+ controls and focus return, and no changed IPC, persistence or permission
+ boundary. Playback and error recovery do not require opening Details.
+- **Specs:** [Live Voice](../03-runtime/live-voice.md),
+ [Live Work](../03-runtime/live-work-session.md),
+ [Component spec](../04-ux/08-component-spec.md#1171-live-voice-preparation-compact-call-bar-and-details),
+ [Settings IA](../04-ux/06-settings-ia.md#voice-experimental).
+- **Acceptance:** C / E / Security / Quality.
+- **Milestone:** Post-MVP experimental interaction maintenance.
+- **Coverage:** Planned targeted component/controller regression coverage and an
+ isolated Electron fixture journey. Existing lifecycle and shortcut tests do
+ not by themselves prove the new four-stage UI or navigation/cleanup races.
+- **Status:** Planned; task-candidate fixture execution is pending. No green E2E
+ or real-provider/device result is claimed for this scenario.
+
### E2E-LIVE-WORK-session-admission
- **Preconditions:** Isolated Live provider fixture, a local AgentHost session,
@@ -50,9 +106,10 @@
through the existing Live adapter callback; do not use a real account or
paid endpoint.
- **Steps:** Start a voice-only call and verify a work candidate is rejected
- without a work scope. Start a second call with an explicitly selected local
- session and context sharing disabled. Submit one declared work request,
- deliver its receipt, route it through the classifier, and inspect the Host
+ without a work scope. Start a second call after opting into work requests and
+ explicitly selecting a local session, with context sharing disabled. Submit
+ one declared work request, deliver its receipt, route it through the
+ classifier, and inspect the Host
admission and `voiceOrigin`. Exercise a busy independent request through the
Host queue, a stale steer, an exact-turn stop, and a terminal event arriving
before the submit promise resolves. Query a recorded terminal result and
@@ -8904,6 +8961,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| Acceptance | Scenarios |
|---|---|
| C / E / F / Quality / Security — Session Todo checklist | E2E-CHAT-session-todo-checklist |
+| C / E / Security / Quality — Live Voice four-stage interaction | E2E-LIVE-VOICE-four-stage-ui |
| C / F — Hourly task updates | E2E-SCHEDULED-manual-to-hourly |
| C / F / Quality — Saved project isolation | E2E-SCHEDULED-manual-workspace-binding |
| C / F / Quality — Desktop automations | E2E-SCHEDULED-desktop-automation-lifecycle |
@@ -8973,6 +9031,7 @@ must keep splitting are covered by `markdown-blocks.test.mjs`.
| Milestone | Scenarios |
|---|---|
+| Post-MVP experimental interaction maintenance | E2E-LIVE-VOICE-four-stage-ui |
| M1 | E2E-001, E2E-002, E2E-003, E2E-028, E2E-029 |
| M2 | E2E-004, E2E-005, E2E-006, E2E-007, E2E-008, E2E-008d, E2E-008e, E2E-009, E2E-010, E2E-011, E2E-011a, E2E-011b, E2E-011d, E2E-011e, E2E-011g, E2E-020, E2E-021, E2E-021a, E2E-027, E2E-031, E2E-036, E2E-037, E2E-042, E2E-087, E2E-088, E2E-088b, E2E-089, E2E-090, E2E-COMPOSER-narrow-controls, E2E-144, E2E-005J, E2E-201, E2E-202, E2E-207, E2E-206 |
| M3 | E2E-012, E2E-013, E2E-014, E2E-015, E2E-016, E2E-017, E2E-018, E2E-019, E2E-040 |
diff --git a/package.json b/package.json
index 649456ff7..10a9fe96a 100644
--- a/package.json
+++ b/package.json
@@ -72,7 +72,8 @@
"test:e2e:session-completion": "node scripts/e2e-session-completion.mjs",
"test:e2e:remote-host": "node scripts/e2e-remote-host.mjs",
"test:e2e:shortcut-settings": "node scripts/test-shortcut-settings.mjs",
- "test:e2e:dialog-overflow": "node scripts/test-dialog-overflow.mjs"
+ "test:e2e:dialog-overflow": "node scripts/test-dialog-overflow.mjs",
+ "test:e2e:live-voice-interaction": "node scripts/test-live-voice-interaction.mjs"
},
"devDependencies": {
"@biomejs/biome": "^2.5.13",
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index 2c2fa8b92..ba935a0e7 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -2444,6 +2444,32 @@ sklm: {
liveVoice: {
...en.liveVoice,
title: "Live-Sprache",
+ prepareCall: "Live-Sprache vorbereiten",
+ details: "Anrufdetails",
+ callActionFailed: "Der Anruf konnte nicht aktualisiert werden. Versuche es erneut oder beende ihn.",
+ workNotConnected: "Dieser Anruf ist nicht mit einer Arbeitssitzung verbunden.",
+ workOptions: "Arbeitssitzung verbinden",
+ allowWork: "Arbeitsaufträge erlauben",
+ noWorkSession: "Wähle oder erstelle eine lokale Arbeitssitzung.",
+ playbackBlocked: "Ton ist pausiert",
+ playbackFailed: "Ton konnte nicht fortgesetzt werden. Versuche es erneut.",
+ mediaReleaseUnconfirmed: "Die Freigabe des Mikrofons konnte nicht bestätigt werden. Starte die App vor einem weiteren Anruf neu.",
+ transcript: "Transkript",
+ transcriptEmpty: "Noch kein Transkript",
+ userSpeaking: "Hört zu",
+ assistantSpeaking: "Spricht",
+ muted: "Mikrofon stummgeschaltet",
+ selectWorkSession: "Arbeitssitzung für den nächsten Anruf",
+ shareContext: "Begrenzten aktuellen Gesprächskontext teilen",
+ contextConsent: "Wenn aktiviert, können bis zu sechs aktuelle reine Textnachrichten von dir und dem Assistenten zur Einordnung von Anfragen an den ausgewählten Sprachanbieter gesendet werden. Tool-Ausgaben, Anhänge und Sprachnachrichten sind ausgeschlossen. Diese Einstellung gilt nur für den nächsten Anruf.",
+ contextShared: "Begrenzter aktueller Gesprächskontext wurde für diesen Anruf geteilt.",
+ contextNotShared: "Der aktuelle Gesprächsverlauf wurde für diesen Anruf nicht geteilt.",
+ createWorkSession: "Neue Arbeitssitzung erstellen",
+ viewWorkSession: "Arbeitssitzung anzeigen",
+ viewingDifferentSession: "Aktuell angezeigt: {{label}}",
+ unknownSession: "eine andere Sitzung",
+ sessionOpenFailed: "Die gebundene Arbeitssitzung konnte nicht geöffnet werden.",
+ sessionCreateFailed: "Arbeitssitzung konnte nicht erstellt werden.",
openWorkSetup: "Sitzung für Live-Arbeitsanruf auswählen",
connectWorkSession: "Mit {{label}} verbinden",
untitledWorkSession: "Unbenannte Sitzung",
@@ -2451,15 +2477,15 @@ sklm: {
workSessionNoContext: "Der aktuelle Chatverlauf wird für diesen Anruf nicht geteilt.",
description: "Sprich direkt mit einem eingerichteten Echtzeit-Sprachanbieter. Live-Sprache ist zunächst deaktiviert.",
enable: "Live-Sprache aktivieren",
- enableDetail: "Mikrofon-Audio wird an den ausgewählten Anbieter gesendet. Agenten, Tools und MCP-Aktionen werden nicht ausgeführt.",
+ enableDetail: "Mikrofon-Audio wird an den ausgewählten Anbieter gesendet. Anrufe sind standardmäßig reine Sprachgespräche; Arbeitsaufträge erfordern eine separate Zustimmung und eine Arbeitssitzung.",
bindingStatus: "Anbieterstatus", ready: "Bereit", provider: "Anbieterkonto", chooseProvider: "Anbieterkonto auswählen",
providerUnavailable: "Ausgewählter Anbieter nicht verfügbar", providerDisabled: "deaktiviert", credentialsMissing: "Zugangsdaten fehlen",
model: "Modell-ID", voice: "Stimme", profile: "Protokollprofil", useForNextCall: "Für den nächsten Anruf verwenden",
bindingLocked: "Anruf läuft", bindingLockedDetail: "Beende den Anruf, um Änderungen an dieser Anbieterbindung anzuwenden.", saveFailed: "Live-Spracheinstellungen konnten nicht gespeichert werden.",
adapters: { "codex-live": { title: "Codex-Konto", description: "Verwendet das ausgewählte Codex-Konto und dessen bestehende Anmeldung." }, "gemini-live": { title: "Gemini Live", description: "Verwendet einen Google-Generative-AI-Anbieter mit API-Schlüssel." }, "openai-realtime": { title: "OpenAI-Realtime-kompatibel", description: "Verwendet einen API-Schlüssel-Anbieter mit explizitem Realtime-Protokollprofil." } },
readiness: { disabled: "Anbieter deaktiviert", "missing-provider": "Anbieter nicht verfügbar", "missing-credentials": "Zugangsdaten fehlen", "wrong-auth-kind": "Authentifizierung nicht unterstützt", "unsupported-adapter": "Adapter nicht unterstützt", "invalid-settings": "Ungültige Einstellungen" },
- openPanel: "Live-Sprache öffnen", start: "Live-Sprache starten", end: "Anruf beenden", mute: "Mikrofon stummschalten", unmute: "Mikrofon aktivieren", resumePlayback: "Ton aktivieren", errorGeneric: "Live-Sprache wurde beendet. Prüfe den Anbieter und versuche es erneut.", microphoneDenied: "Erlaube den Mikrofonzugriff in Browser- und Systemeinstellungen und versuche es erneut.", microphoneUnavailable: "Kein verwendbares Mikrofon gefunden. Prüfe das ausgewählte Gerät und seine Verbindung.", microphoneBusy: "Das Mikrofon wird von einer anderen Aufnahme verwendet. Beende sie, bevor du Live-Sprache startest.", noProvider: "Wähle unter Einstellungen → Sprache einen unterstützten Anbieter.", enableInSettings: "Aktiviere Live-Sprache unter Einstellungen → Sprache.",
- phase: { idle: "Aus", preparing: "Wird vorbereitet", "acquiring-mic": "Warte auf Mikrofon", negotiating: "Aushandlung", connecting: "Verbindung wird hergestellt", connected: "Verbunden", reconnecting: "Verbindung wird wiederhergestellt", closing: "Wird beendet", ended: "Beendet", failed: "Gestoppt" },
+ openPanel: "Live-Sprache öffnen", start: "Live-Sprache starten", end: "Anruf beenden", mute: "Mikrofon stummschalten", unmute: "Mikrofon aktivieren", resumePlayback: "Ton fortsetzen", errorGeneric: "Live-Sprache wurde beendet. Prüfe den Anbieter und versuche es erneut.", microphoneDenied: "Erlaube den Mikrofonzugriff in Browser- und Systemeinstellungen und versuche es erneut.", microphoneUnavailable: "Kein verwendbares Mikrofon gefunden. Prüfe das ausgewählte Gerät und seine Verbindung.", microphoneBusy: "Das Mikrofon wird von einer anderen Aufnahme verwendet. Beende sie, bevor du Live-Sprache startest.", noProvider: "Wähle unter Einstellungen → Sprache einen unterstützten Anbieter.", enableInSettings: "Aktiviere Live-Sprache unter Einstellungen → Sprache.",
+ phase: { idle: "Aus", preparing: "Wird vorbereitet", "acquiring-mic": "Warte auf Mikrofon", negotiating: "Aushandlung", connecting: "Verbindung wird hergestellt…", connected: "Verbunden", reconnecting: "Verbindung wird wiederhergestellt", closing: "Wird beendet…", ended: "Beendet", failed: "Gestoppt" },
},
"errors": {
"HOST_UNAVAILABLE": "Der lokale Dienst ist nicht verfügbar",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index 3bfd21b9d..e8a57b26a 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -2490,9 +2490,21 @@ importConfirm: "Imported extensions run inside the agent process with the same a
},
liveVoice: {
title: "Live voice",
+ prepareCall: "Prepare Live voice",
+ details: "Call details",
+ callActionFailed: "Couldn't update the call. Try again or end it.",
+ workNotConnected: "This call isn't connected to a work session.",
+ workOptions: "Connect a work session",
+ allowWork: "Allow work requests",
+ noWorkSession: "Choose or create a local work session.",
+ playbackBlocked: "Sound is paused",
+ playbackFailed: "Couldn't resume sound. Try again.",
+ mediaReleaseUnconfirmed: "Microphone release could not be confirmed. Restart the app before another call.",
+ transcript: "Transcript",
+ transcriptEmpty: "No transcript yet",
description: "Talk directly with a configured real-time voice provider. Live voice is off until you enable it.",
enable: "Enable Live voice",
- enableDetail: "Live voice sends microphone audio to the provider you select. It does not run agents, tools, or MCP actions.",
+ enableDetail: "Microphone audio goes to your selected provider. Calls are voice-only by default; work requests require a separate opt-in and work session.",
bindingStatus: "Provider status",
ready: "Ready",
provider: "Provider account",
@@ -2590,7 +2602,7 @@ importConfirm: "Imported extensions run inside the agent process with the same a
end: "End call",
mute: "Mute microphone",
unmute: "Unmute microphone",
- resumePlayback: "Enable sound",
+ resumePlayback: "Resume sound",
errorGeneric: "Live voice stopped. Check the provider and try again.",
microphoneDenied: "Allow microphone access in your browser and system settings, then try again.",
microphoneUnavailable: "No usable microphone was found. Check the selected device and its connection.",
@@ -2605,10 +2617,10 @@ importConfirm: "Imported extensions run inside the agent process with the same a
preparing: "Preparing",
"acquiring-mic": "Waiting for microphone",
negotiating: "Negotiating",
- connecting: "Connecting",
+ connecting: "Connecting…",
connected: "Connected",
reconnecting: "Reconnecting",
- closing: "Ending",
+ closing: "Ending…",
ended: "Ended",
failed: "Stopped",
},
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index fdf61f608..a3844601f 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -2443,18 +2443,47 @@ sklm: {
},
liveVoice: {
...en.liveVoice,
+ prepareCall: "Preparar voz en tiempo real",
+ details: "Detalles de la llamada",
+ callActionFailed: "No se pudo actualizar la llamada. Inténtalo de nuevo o finalízala.",
+ workNotConnected: "Esta llamada no está conectada a una sesión de trabajo.",
+ workOptions: "Conectar una sesión de trabajo",
+ allowWork: "Permitir solicitudes de trabajo",
+ noWorkSession: "Elige o crea una sesión de trabajo local.",
+ playbackBlocked: "El sonido está en pausa",
+ playbackFailed: "No se pudo reanudar el sonido. Inténtalo de nuevo.",
+ mediaReleaseUnconfirmed: "No se pudo confirmar la liberación del micrófono. Reinicia la aplicación antes de otra llamada.",
+ transcript: "Transcripción",
+ transcriptEmpty: "Aún no hay transcripción",
+ userSpeaking: "Escuchando",
+ assistantSpeaking: "Hablando",
+ muted: "Micrófono silenciado",
+ selectWorkSession: "Sesión de trabajo para la próxima llamada",
+ shareContext: "Compartir contexto reciente limitado de la conversación",
+ contextConsent: "Si se activa, se pueden compartir hasta seis mensajes recientes de texto del usuario y del asistente con el proveedor de voz seleccionado para clasificar solicitudes. Se excluyen los resultados de herramientas, los archivos adjuntos y los mensajes de voz. Esta opción solo se aplica a la próxima llamada.",
+ contextShared: "Se compartió contexto reciente limitado de la conversación para esta llamada.",
+ contextNotShared: "No se compartió el historial reciente de la conversación para esta llamada.",
+ createWorkSession: "Crear una sesión de trabajo",
+ viewWorkSession: "Ver sesión de trabajo",
+ viewingDifferentSession: "Viendo ahora: {{label}}",
+ unknownSession: "otra sesión",
+ sessionOpenFailed: "No se pudo abrir la sesión de trabajo vinculada.",
+ sessionCreateFailed: "No se pudo crear una sesión de trabajo.",
+ microphoneDenied: "Permite el acceso al micrófono en los ajustes del navegador y del sistema e inténtalo de nuevo.",
+ microphoneUnavailable: "No se encontró ningún micrófono disponible. Comprueba el dispositivo seleccionado y su conexión.",
+ microphoneBusy: "Otra grabación está usando el micrófono. Detenla antes de iniciar la voz en tiempo real.",
title: "Voz en tiempo real", description: "Habla directamente con un proveedor de voz en tiempo real configurado. La función está desactivada hasta que la habilites.",
openWorkSetup: "Elegir una sesión para una llamada de trabajo",
connectWorkSession: "Conectar con {{label}}",
untitledWorkSession: "Sesión sin título",
boundWorkSession: "Sesión de trabajo vinculada: {{label}}",
workSessionNoContext: "Esta llamada no comparte el historial reciente del chat.",
- enable: "Activar voz en tiempo real", enableDetail: "El audio del micrófono se envía al proveedor seleccionado. No ejecuta agentes, herramientas ni acciones MCP.",
+ enable: "Activar voz en tiempo real", enableDetail: "El audio del micrófono se envía al proveedor seleccionado. Las llamadas son solo de voz por defecto; las solicitudes de trabajo requieren autorización aparte y una sesión de trabajo.",
bindingStatus: "Estado del proveedor", ready: "Listo", provider: "Cuenta del proveedor", chooseProvider: "Elige una cuenta", providerUnavailable: "El proveedor seleccionado no está disponible", providerDisabled: "desactivado", credentialsMissing: "faltan credenciales", model: "ID del modelo", voice: "Voz", profile: "Perfil del protocolo", useForNextCall: "Usar en la próxima llamada", bindingLocked: "Llamada en curso", bindingLockedDetail: "Termina la llamada para aplicar cambios a esta cuenta.", saveFailed: "No se pudo guardar la configuración de voz en tiempo real.",
adapters: { "codex-live": { title: "Cuenta de Codex", description: "Usa la cuenta de Codex seleccionada y su inicio de sesión existente." }, "gemini-live": { title: "Gemini Live", description: "Usa un proveedor de Google Generative AI con una clave API." }, "openai-realtime": { title: "Compatible con OpenAI Realtime", description: "Usa un proveedor con clave API y un perfil Realtime explícito." } },
readiness: { disabled: "Proveedor desactivado", "missing-provider": "Proveedor no disponible", "missing-credentials": "Faltan credenciales", "wrong-auth-kind": "Autenticación no compatible", "unsupported-adapter": "Adaptador no compatible", "invalid-settings": "Configuración no válida" },
- openPanel: "Abrir controles de voz", start: "Iniciar voz en tiempo real", end: "Finalizar llamada", mute: "Silenciar micrófono", unmute: "Activar micrófono", resumePlayback: "Activar sonido", errorGeneric: "La voz en tiempo real se detuvo. Revisa el proveedor e inténtalo de nuevo.", noProvider: "Elige un proveedor compatible en Ajustes → Voz.", enableInSettings: "Activa la voz en tiempo real en Ajustes → Voz.",
- phase: { idle: "Desactivado", preparing: "Preparando", "acquiring-mic": "Esperando el micrófono", negotiating: "Negociando", connecting: "Conectando", connected: "Conectado", reconnecting: "Reconectando", closing: "Finalizando", ended: "Finalizado", failed: "Detenido" },
+ openPanel: "Abrir controles de voz", start: "Iniciar voz en tiempo real", end: "Finalizar llamada", mute: "Silenciar micrófono", unmute: "Activar micrófono", resumePlayback: "Reanudar sonido", errorGeneric: "La voz en tiempo real se detuvo. Revisa el proveedor e inténtalo de nuevo.", noProvider: "Elige un proveedor compatible en Ajustes → Voz.", enableInSettings: "Activa la voz en tiempo real en Ajustes → Voz.",
+ phase: { idle: "Desactivado", preparing: "Preparando", "acquiring-mic": "Esperando el micrófono", negotiating: "Negociando", connecting: "Conectando…", connected: "Conectado", reconnecting: "Reconectando", closing: "Finalizando…", ended: "Finalizado", failed: "Detenido" },
},
"errors": {
"HOST_UNAVAILABLE": "El servicio local no está disponible",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 29b7ad572..4b4eca98d 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -2443,18 +2443,47 @@ sklm: {
},
liveVoice: {
...en.liveVoice,
+ prepareCall: "Préparer la voix en direct",
+ details: "Détails de l’appel",
+ callActionFailed: "Impossible de mettre à jour l’appel. Réessayez ou terminez-le.",
+ workNotConnected: "Cet appel n’est pas connecté à une session de travail.",
+ workOptions: "Connecter une session de travail",
+ allowWork: "Autoriser les demandes de travail",
+ noWorkSession: "Choisissez ou créez une session de travail locale.",
+ playbackBlocked: "Le son est en pause",
+ playbackFailed: "Impossible de reprendre le son. Réessayez.",
+ mediaReleaseUnconfirmed: "La libération du microphone n’a pas pu être confirmée. Redémarrez l’application avant un autre appel.",
+ transcript: "Transcription",
+ transcriptEmpty: "Aucune transcription pour le moment",
+ userSpeaking: "À l’écoute",
+ assistantSpeaking: "En train de parler",
+ muted: "Microphone coupé",
+ selectWorkSession: "Session de travail pour le prochain appel",
+ shareContext: "Partager un contexte récent limité de la conversation",
+ contextConsent: "Si cette option est activée, jusqu’à six messages récents en texte simple de l’utilisateur et de l’assistant peuvent être partagés avec le fournisseur vocal choisi pour classer les demandes. Les sorties d’outils, les pièces jointes et les messages vocaux sont exclus. Cette option ne s’applique qu’au prochain appel.",
+ contextShared: "Un contexte récent limité de la conversation a été partagé pour cet appel.",
+ contextNotShared: "L’historique récent de la conversation n’a pas été partagé pour cet appel.",
+ createWorkSession: "Créer une session de travail",
+ viewWorkSession: "Voir la session de travail",
+ viewingDifferentSession: "Affichage actuel : {{label}}",
+ unknownSession: "une autre session",
+ sessionOpenFailed: "Impossible d’ouvrir la session de travail associée.",
+ sessionCreateFailed: "Impossible de créer une session de travail.",
+ microphoneDenied: "Autorisez l’accès au microphone dans les réglages du navigateur et du système, puis réessayez.",
+ microphoneUnavailable: "Aucun microphone utilisable n’a été trouvé. Vérifiez l’appareil sélectionné et sa connexion.",
+ microphoneBusy: "Le microphone est utilisé par un autre enregistrement. Arrêtez-le avant de démarrer la voix en direct.",
title: "Voix en direct", description: "Parlez directement avec un fournisseur vocal configuré en temps réel. La fonction reste désactivée tant que vous ne l’activez pas.",
openWorkSetup: "Choisir une session pour un appel de travail",
connectWorkSession: "Se connecter à {{label}}",
untitledWorkSession: "Session sans titre",
boundWorkSession: "Session de travail associée : {{label}}",
workSessionNoContext: "Cet appel ne partage pas l’historique récent de la conversation.",
- enable: "Activer la voix en direct", enableDetail: "L’audio du microphone est envoyé au fournisseur choisi. Aucun agent, outil ou action MCP n’est exécuté.",
+ enable: "Activer la voix en direct", enableDetail: "L’audio du microphone est envoyé au fournisseur choisi. Les appels sont uniquement vocaux par défaut ; les demandes de travail nécessitent une autorisation distincte et une session de travail.",
bindingStatus: "État du fournisseur", ready: "Prêt", provider: "Compte fournisseur", chooseProvider: "Choisir un compte fournisseur", providerUnavailable: "Le fournisseur sélectionné est indisponible", providerDisabled: "désactivé", credentialsMissing: "identifiants manquants", model: "ID du modèle", voice: "Voix", profile: "Profil du protocole", useForNextCall: "Utiliser au prochain appel", bindingLocked: "Appel en cours", bindingLockedDetail: "Terminez l’appel pour appliquer les changements de ce compte.", saveFailed: "Impossible d’enregistrer les paramètres de voix en direct.",
adapters: { "codex-live": { title: "Compte Codex", description: "Utilise le compte Codex sélectionné et sa connexion existante." }, "gemini-live": { title: "Gemini Live", description: "Utilise un fournisseur Google Generative AI avec une clé API." }, "openai-realtime": { title: "Compatible OpenAI Realtime", description: "Utilise un fournisseur avec clé API et un profil Realtime explicite." } },
readiness: { disabled: "Fournisseur désactivé", "missing-provider": "Fournisseur indisponible", "missing-credentials": "Identifiants manquants", "wrong-auth-kind": "Authentification non prise en charge", "unsupported-adapter": "Adaptateur non pris en charge", "invalid-settings": "Paramètres invalides" },
- openPanel: "Ouvrir les commandes vocales", start: "Démarrer la voix en direct", end: "Terminer l’appel", mute: "Couper le microphone", unmute: "Activer le microphone", resumePlayback: "Activer le son", errorGeneric: "La voix en direct s’est arrêtée. Vérifiez le fournisseur et réessayez.", noProvider: "Choisissez un fournisseur compatible dans Réglages → Voix.", enableInSettings: "Activez la voix en direct dans Réglages → Voix.",
- phase: { idle: "Désactivée", preparing: "Préparation", "acquiring-mic": "En attente du microphone", negotiating: "Négociation", connecting: "Connexion", connected: "Connectée", reconnecting: "Reconnexion", closing: "Arrêt", ended: "Terminée", failed: "Arrêtée" },
+ openPanel: "Ouvrir les commandes vocales", start: "Démarrer la voix en direct", end: "Terminer l’appel", mute: "Couper le microphone", unmute: "Activer le microphone", resumePlayback: "Reprendre le son", errorGeneric: "La voix en direct s’est arrêtée. Vérifiez le fournisseur et réessayez.", noProvider: "Choisissez un fournisseur compatible dans Réglages → Voix.", enableInSettings: "Activez la voix en direct dans Réglages → Voix.",
+ phase: { idle: "Désactivée", preparing: "Préparation", "acquiring-mic": "En attente du microphone", negotiating: "Négociation", connecting: "Connexion…", connected: "Connectée", reconnecting: "Reconnexion", closing: "Arrêt…", ended: "Terminée", failed: "Arrêtée" },
},
"errors": {
"HOST_UNAVAILABLE": "Le service local n'est pas disponible",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index 0cf07418e..7036a11f3 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -2479,18 +2479,47 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
},
liveVoice: {
...en.liveVoice,
+ prepareCall: "실시간 음성 준비",
+ details: "통화 상세 정보",
+ callActionFailed: "통화를 업데이트하지 못했습니다. 다시 시도하거나 통화를 종료하세요.",
+ workNotConnected: "이 통화는 작업 세션에 연결되어 있지 않습니다.",
+ workOptions: "작업 세션 연결",
+ allowWork: "작업 요청 허용",
+ noWorkSession: "로컬 작업 세션을 선택하거나 만드세요.",
+ playbackBlocked: "소리 재생이 일시 중지되었습니다",
+ playbackFailed: "소리를 다시 재생하지 못했습니다. 다시 시도하세요.",
+ mediaReleaseUnconfirmed: "마이크 해제를 확인할 수 없습니다. 다음 통화 전에 앱을 다시 시작하세요.",
+ transcript: "대화 기록",
+ transcriptEmpty: "아직 대화 기록이 없습니다",
+ userSpeaking: "듣는 중",
+ assistantSpeaking: "말하는 중",
+ muted: "마이크 음소거됨",
+ selectWorkSession: "다음 통화에 사용할 작업 세션",
+ shareContext: "제한된 최근 대화 맥락 공유",
+ contextConsent: "활성화하면 요청을 분류하기 위해 최근 사용자 및 어시스턴트의 일반 텍스트 메시지를 최대 6개까지 선택한 음성 제공자와 공유할 수 있습니다. 도구 출력, 첨부 파일, 음성 메시지는 제외됩니다. 이 설정은 다음 통화에만 적용됩니다.",
+ contextShared: "이 통화에 제한된 최근 대화 맥락을 공유했습니다.",
+ contextNotShared: "이 통화에는 최근 대화 기록을 공유하지 않았습니다.",
+ createWorkSession: "새 작업 세션 만들기",
+ viewWorkSession: "작업 세션 보기",
+ viewingDifferentSession: "현재 보는 세션: {{label}}",
+ unknownSession: "다른 세션",
+ sessionOpenFailed: "연결된 작업 세션을 열지 못했습니다.",
+ sessionCreateFailed: "작업 세션을 만들지 못했습니다.",
+ microphoneDenied: "브라우저 및 시스템 설정에서 마이크 접근을 허용한 후 다시 시도하세요.",
+ microphoneUnavailable: "사용 가능한 마이크를 찾지 못했습니다. 선택한 장치와 연결 상태를 확인하세요.",
+ microphoneBusy: "다른 녹음에서 마이크를 사용 중입니다. 실시간 음성을 시작하기 전에 녹음을 중지하세요.",
title: "실시간 음성", description: "설정된 실시간 음성 제공자와 직접 대화합니다. 활성화하기 전까지 꺼져 있습니다.",
openWorkSetup: "실시간 작업 통화에 사용할 세션 선택",
connectWorkSession: "{{label}}에 연결",
untitledWorkSession: "제목 없는 세션",
boundWorkSession: "작업 세션 연결됨: {{label}}",
workSessionNoContext: "이 통화에서는 최근 채팅 기록을 공유하지 않습니다.",
- enable: "실시간 음성 사용", enableDetail: "마이크 오디오가 선택한 제공자에게 전송됩니다. 에이전트, 도구 또는 MCP 작업은 실행되지 않습니다.",
+ enable: "실시간 음성 사용", enableDetail: "마이크 오디오가 선택한 제공자에게 전송됩니다. 통화는 기본적으로 음성 대화만 지원하며, 작업 요청에는 별도 동의와 작업 세션이 필요합니다.",
bindingStatus: "제공자 상태", ready: "준비됨", provider: "제공자 계정", chooseProvider: "제공자 계정 선택", providerUnavailable: "선택한 제공자를 사용할 수 없습니다", providerDisabled: "비활성화됨", credentialsMissing: "인증 정보 없음", model: "모델 ID", voice: "음성", profile: "프로토콜 프로필", useForNextCall: "다음 통화에 사용", bindingLocked: "통화 중", bindingLockedDetail: "이 제공자 연결의 변경 사항을 적용하려면 통화를 종료하세요.", saveFailed: "실시간 음성 설정을 저장하지 못했습니다.",
adapters: { "codex-live": { title: "Codex 계정", description: "선택한 Codex 계정과 기존 로그인을 사용합니다." }, "gemini-live": { title: "Gemini Live", description: "API 키가 있는 Google Generative AI 제공자를 사용합니다." }, "openai-realtime": { title: "OpenAI Realtime 호환", description: "API 키 제공자와 명시적인 Realtime 프로토콜 프로필을 사용합니다." } },
readiness: { disabled: "제공자 비활성화됨", "missing-provider": "제공자를 사용할 수 없음", "missing-credentials": "인증 정보 없음", "wrong-auth-kind": "지원되지 않는 인증 방식", "unsupported-adapter": "지원되지 않는 어댑터", "invalid-settings": "잘못된 설정" },
- openPanel: "실시간 음성 제어 열기", start: "실시간 음성 시작", end: "통화 종료", mute: "마이크 음소거", unmute: "마이크 음소거 해제", resumePlayback: "소리 사용", errorGeneric: "실시간 음성이 중지되었습니다. 제공자 설정을 확인하고 다시 시도하세요.", noProvider: "설정 → 음성에서 지원되는 제공자를 선택하세요.", enableInSettings: "설정 → 음성에서 실시간 음성을 활성화하세요.",
- phase: { idle: "꺼짐", preparing: "준비 중", "acquiring-mic": "마이크 대기 중", negotiating: "협상 중", connecting: "연결 중", connected: "연결됨", reconnecting: "재연결 중", closing: "종료 중", ended: "종료됨", failed: "중지됨" },
+ openPanel: "실시간 음성 제어 열기", start: "실시간 음성 시작", end: "통화 종료", mute: "마이크 음소거", unmute: "마이크 음소거 해제", resumePlayback: "소리 재생 재개", errorGeneric: "실시간 음성이 중지되었습니다. 제공자 설정을 확인하고 다시 시도하세요.", noProvider: "설정 → 음성에서 지원되는 제공자를 선택하세요.", enableInSettings: "설정 → 음성에서 실시간 음성을 활성화하세요.",
+ phase: { idle: "꺼짐", preparing: "준비 중", "acquiring-mic": "마이크 대기 중", negotiating: "협상 중", connecting: "연결 중…", connected: "연결됨", reconnecting: "재연결 중", closing: "종료 중…", ended: "종료됨", failed: "중지됨" },
},
errors: {
HOST_UNAVAILABLE: "로컬 서비스를 사용할 수 없습니다",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index eaf7eb827..2249ddf91 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -2399,18 +2399,47 @@ export const ptBR = {
},
liveVoice: {
...en.liveVoice,
+ prepareCall: "Preparar voz ao vivo",
+ details: "Detalhes da chamada",
+ callActionFailed: "Não foi possível atualizar a chamada. Tente novamente ou encerre-a.",
+ workNotConnected: "Esta chamada não está conectada a uma sessão de trabalho.",
+ workOptions: "Conectar uma sessão de trabalho",
+ allowWork: "Permitir solicitações de trabalho",
+ noWorkSession: "Escolha ou crie uma sessão de trabalho local.",
+ playbackBlocked: "O som está pausado",
+ playbackFailed: "Não foi possível retomar o som. Tente novamente.",
+ mediaReleaseUnconfirmed: "Não foi possível confirmar a liberação do microfone. Reinicie o aplicativo antes de outra chamada.",
+ transcript: "Transcrição",
+ transcriptEmpty: "Ainda não há transcrição",
+ userSpeaking: "Ouvindo",
+ assistantSpeaking: "Falando",
+ muted: "Microfone silenciado",
+ selectWorkSession: "Sessão de trabalho para a próxima chamada",
+ shareContext: "Compartilhar contexto recente limitado da conversa",
+ contextConsent: "Se ativada, esta opção permite compartilhar até seis mensagens recentes de texto do usuário e do assistente com o provedor de voz escolhido para classificar solicitações. Saídas de ferramentas, anexos e mensagens de voz são excluídos. Esta configuração vale apenas para a próxima chamada.",
+ contextShared: "Um contexto recente limitado da conversa foi compartilhado nesta chamada.",
+ contextNotShared: "O histórico recente da conversa não foi compartilhado nesta chamada.",
+ createWorkSession: "Criar uma sessão de trabalho",
+ viewWorkSession: "Ver sessão de trabalho",
+ viewingDifferentSession: "Visualizando agora: {{label}}",
+ unknownSession: "outra sessão",
+ sessionOpenFailed: "Não foi possível abrir a sessão de trabalho vinculada.",
+ sessionCreateFailed: "Não foi possível criar uma sessão de trabalho.",
+ microphoneDenied: "Permita o acesso ao microfone nas configurações do navegador e do sistema e tente novamente.",
+ microphoneUnavailable: "Nenhum microfone utilizável foi encontrado. Confira o dispositivo selecionado e sua conexão.",
+ microphoneBusy: "O microfone está sendo usado por outra gravação. Pare-a antes de iniciar a voz ao vivo.",
title: "Voz ao vivo", description: "Converse diretamente com um provedor de voz em tempo real configurado. A voz ao vivo fica desativada até você habilitá-la.",
openWorkSetup: "Escolher uma sessão para uma chamada de trabalho",
connectWorkSession: "Conectar a {{label}}",
untitledWorkSession: "Sessão sem título",
boundWorkSession: "Sessão de trabalho vinculada: {{label}}",
workSessionNoContext: "Esta chamada não compartilha o histórico recente do chat.",
- enable: "Ativar voz ao vivo", enableDetail: "O áudio do microfone é enviado ao provedor escolhido. Agentes, ferramentas e ações MCP não são executados.",
+ enable: "Ativar voz ao vivo", enableDetail: "O áudio do microfone é enviado ao provedor escolhido. Por padrão, as chamadas são apenas de voz; solicitações de trabalho exigem autorização separada e uma sessão de trabalho.",
bindingStatus: "Status do provedor", ready: "Pronto", provider: "Conta do provedor", chooseProvider: "Escolha uma conta", providerUnavailable: "O provedor selecionado está indisponível", providerDisabled: "desativado", credentialsMissing: "credenciais ausentes", model: "ID do modelo", voice: "Voz", profile: "Perfil do protocolo", useForNextCall: "Usar na próxima chamada", bindingLocked: "Chamada em andamento", bindingLockedDetail: "Encerre a chamada para aplicar as alterações desta conta.", saveFailed: "Não foi possível salvar as configurações de voz ao vivo.",
adapters: { "codex-live": { title: "Conta Codex", description: "Usa a conta Codex selecionada e o login existente." }, "gemini-live": { title: "Gemini Live", description: "Usa um provedor Google Generative AI com chave de API." }, "openai-realtime": { title: "Compatível com OpenAI Realtime", description: "Usa um provedor com chave de API e perfil Realtime explícito." } },
readiness: { disabled: "Provedor desativado", "missing-provider": "Provedor indisponível", "missing-credentials": "Credenciais ausentes", "wrong-auth-kind": "Autenticação incompatível", "unsupported-adapter": "Adaptador incompatível", "invalid-settings": "Configuração inválida" },
- openPanel: "Abrir controles de voz", start: "Iniciar voz ao vivo", end: "Encerrar chamada", mute: "Silenciar microfone", unmute: "Ativar microfone", resumePlayback: "Ativar som", errorGeneric: "A voz ao vivo foi interrompida. Confira o provedor e tente novamente.", noProvider: "Escolha um provedor compatível em Configurações → Voz.", enableInSettings: "Ative a voz ao vivo em Configurações → Voz.",
- phase: { idle: "Desativada", preparing: "Preparando", "acquiring-mic": "Aguardando microfone", negotiating: "Negociando", connecting: "Conectando", connected: "Conectado", reconnecting: "Reconectando", closing: "Encerrando", ended: "Encerrada", failed: "Interrompida" },
+ openPanel: "Abrir controles de voz", start: "Iniciar voz ao vivo", end: "Encerrar chamada", mute: "Silenciar microfone", unmute: "Ativar microfone", resumePlayback: "Retomar som", errorGeneric: "A voz ao vivo foi interrompida. Confira o provedor e tente novamente.", noProvider: "Escolha um provedor compatível em Configurações → Voz.", enableInSettings: "Ative a voz ao vivo em Configurações → Voz.",
+ phase: { idle: "Desativada", preparing: "Preparando", "acquiring-mic": "Aguardando microfone", negotiating: "Negociando", connecting: "Conectando…", connected: "Conectado", reconnecting: "Reconectando", closing: "Encerrando…", ended: "Encerrada", failed: "Interrompida" },
},
errors: {
HOST_UNAVAILABLE: "O serviço local está indisponível",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 94cb8af7b..811d297d4 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -2469,18 +2469,47 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
},
liveVoice: {
...en.liveVoice,
+ prepareCall: "Canlı sesi hazırla",
+ details: "Arama ayrıntıları",
+ callActionFailed: "Arama güncellenemedi. Tekrar deneyin veya aramayı bitirin.",
+ workNotConnected: "Bu arama bir çalışma oturumuna bağlı değil.",
+ workOptions: "Çalışma oturumu bağla",
+ allowWork: "Çalışma isteklerine izin ver",
+ noWorkSession: "Yerel bir çalışma oturumu seçin veya oluşturun.",
+ playbackBlocked: "Ses duraklatıldı",
+ playbackFailed: "Ses sürdürülemedi. Tekrar deneyin.",
+ mediaReleaseUnconfirmed: "Mikrofonun serbest bırakıldığı doğrulanamadı. Başka bir aramadan önce uygulamayı yeniden başlatın.",
+ transcript: "Konuşma dökümü",
+ transcriptEmpty: "Henüz konuşma dökümü yok",
+ userSpeaking: "Dinliyor",
+ assistantSpeaking: "Konuşuyor",
+ muted: "Mikrofon sessizde",
+ selectWorkSession: "Sonraki arama için çalışma oturumu",
+ shareContext: "Son konuşmadan sınırlı bağlam paylaş",
+ contextConsent: "Etkinleştirilirse istekleri sınıflandırmak için kullanıcının ve asistanın son düz metin mesajlarından en fazla altısı seçilen ses sağlayıcısıyla paylaşılabilir. Araç çıktıları, ekler ve sesli mesajlar paylaşılmaz. Bu ayar yalnızca sonraki arama için geçerlidir.",
+ contextShared: "Bu arama için son konuşmadan sınırlı bağlam paylaşıldı.",
+ contextNotShared: "Bu arama için son konuşma geçmişi paylaşılmadı.",
+ createWorkSession: "Yeni çalışma oturumu oluştur",
+ viewWorkSession: "Çalışma oturumunu görüntüle",
+ viewingDifferentSession: "Şu anda görüntülenen: {{label}}",
+ unknownSession: "başka bir oturum",
+ sessionOpenFailed: "Bağlı çalışma oturumu açılamadı.",
+ sessionCreateFailed: "Çalışma oturumu oluşturulamadı.",
+ microphoneDenied: "Tarayıcı ve sistem ayarlarından mikrofon erişimine izin verip tekrar deneyin.",
+ microphoneUnavailable: "Kullanılabilir mikrofon bulunamadı. Seçilen cihazı ve bağlantısını kontrol edin.",
+ microphoneBusy: "Mikrofon başka bir kayıt tarafından kullanılıyor. Canlı sesi başlatmadan önce kaydı durdurun.",
title: "Canlı ses", description: "Yapılandırılmış bir gerçek zamanlı ses sağlayıcısıyla doğrudan konuşun. Etkinleştirene kadar canlı ses kapalıdır.",
openWorkSetup: "Canlı çalışma araması için oturum seçin",
connectWorkSession: "{{label}} oturumuna bağlan",
untitledWorkSession: "Başlıksız oturum",
boundWorkSession: "Çalışma oturumuna bağlı: {{label}}",
workSessionNoContext: "Bu aramada son sohbet geçmişi paylaşılmaz.",
- enable: "Canlı sesi etkinleştir", enableDetail: "Mikrofon sesi seçtiğiniz sağlayıcıya gönderilir. Agent, araç veya MCP işlemleri çalıştırılmaz.",
+ enable: "Canlı sesi etkinleştir", enableDetail: "Mikrofon sesi seçtiğiniz sağlayıcıya gönderilir. Aramalar varsayılan olarak yalnızca sesli görüşmedir; çalışma istekleri için ayrıca izin vermeniz ve bir çalışma oturumu seçmeniz gerekir.",
bindingStatus: "Sağlayıcı durumu", ready: "Hazır", provider: "Sağlayıcı hesabı", chooseProvider: "Sağlayıcı hesabı seçin", providerUnavailable: "Seçilen sağlayıcı kullanılamıyor", providerDisabled: "devre dışı", credentialsMissing: "kimlik bilgileri eksik", model: "Model kimliği", voice: "Ses", profile: "Protokol profili", useForNextCall: "Sonraki aramada kullan", bindingLocked: "Arama sürüyor", bindingLockedDetail: "Bu sağlayıcı bağlantısındaki değişiklikleri uygulamak için aramayı bitirin.", saveFailed: "Canlı ses ayarları kaydedilemedi.",
adapters: { "codex-live": { title: "Codex hesabı", description: "Seçilen Codex hesabını ve mevcut oturum açma bilgisini kullanır." }, "gemini-live": { title: "Gemini Live", description: "API anahtarı olan bir Google Generative AI sağlayıcısı kullanır." }, "openai-realtime": { title: "OpenAI Realtime uyumlu", description: "API anahtarı sağlayıcısını ve açıkça seçilmiş Realtime protokol profilini kullanır." } },
readiness: { disabled: "Sağlayıcı devre dışı", "missing-provider": "Sağlayıcı kullanılamıyor", "missing-credentials": "Kimlik bilgileri eksik", "wrong-auth-kind": "Kimlik doğrulama desteklenmiyor", "unsupported-adapter": "Adaptör desteklenmiyor", "invalid-settings": "Ayarlar geçersiz" },
- openPanel: "Canlı ses denetimlerini aç", start: "Canlı sesi başlat", end: "Aramayı bitir", mute: "Mikrofonu sessize al", unmute: "Mikrofonun sesini aç", resumePlayback: "Sesi etkinleştir", errorGeneric: "Canlı ses durdu. Sağlayıcıyı kontrol edip tekrar deneyin.", noProvider: "Ayarlar → Ses bölümünden desteklenen bir sağlayıcı seçin.", enableInSettings: "Canlı sesi Ayarlar → Ses bölümünden etkinleştirin.",
- phase: { idle: "Kapalı", preparing: "Hazırlanıyor", "acquiring-mic": "Mikrofon bekleniyor", negotiating: "Anlaşılıyor", connecting: "Bağlanıyor", connected: "Bağlandı", reconnecting: "Yeniden bağlanıyor", closing: "Sonlandırılıyor", ended: "Sonlandı", failed: "Durduruldu" },
+ openPanel: "Canlı ses denetimlerini aç", start: "Canlı sesi başlat", end: "Aramayı bitir", mute: "Mikrofonu sessize al", unmute: "Mikrofonun sesini aç", resumePlayback: "Sesi sürdür", errorGeneric: "Canlı ses durdu. Sağlayıcıyı kontrol edip tekrar deneyin.", noProvider: "Ayarlar → Ses bölümünden desteklenen bir sağlayıcı seçin.", enableInSettings: "Canlı sesi Ayarlar → Ses bölümünden etkinleştirin.",
+ phase: { idle: "Kapalı", preparing: "Hazırlanıyor", "acquiring-mic": "Mikrofon bekleniyor", negotiating: "Anlaşılıyor", connecting: "Bağlanıyor…", connected: "Bağlandı", reconnecting: "Yeniden bağlanıyor", closing: "Sonlandırılıyor…", ended: "Sonlandı", failed: "Durduruldu" },
},
errors: {
HOST_UNAVAILABLE: "Yerel servis kullanılamıyor",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index 4d38cea1f..756f9fcf0 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -2433,9 +2433,24 @@ sklm: {
liveVoice: {
...en.liveVoice,
title: "实时语音",
+ prepareCall: "准备语音",
+ details: "通话详情",
+ callActionFailed: "无法更新通话。请重试或结束通话。",
+ workNotConnected: "此通话未连接工作会话。",
+ workOptions: "连接工作会话",
+ allowWork: "允许发起工作请求",
+ noWorkSession: "请选择或创建本地工作会话。",
+ playbackBlocked: "声音播放已暂停",
+ playbackFailed: "无法恢复播放,请重试。",
+ mediaReleaseUnconfirmed: "无法确认麦克风已释放。请重启应用后再通话。",
+ transcript: "转录",
+ transcriptEmpty: "暂无转录",
+ userSpeaking: "正在聆听",
+ assistantSpeaking: "正在讲话",
+ muted: "麦克风已静音",
description: "直接与已配置的实时语音服务交谈。启用前,实时语音处于关闭状态。",
enable: "启用实时语音",
- enableDetail: "麦克风音频会发送给你选择的服务。此功能不会运行 Agent、工具或 MCP 操作。",
+ enableDetail: "麦克风音频会发送给你选择的服务。通话默认仅用于语音交流;发起工作请求需单独授权并选择工作会话。",
bindingStatus: "服务状态",
ready: "就绪",
provider: "服务账号",
@@ -2526,14 +2541,14 @@ sklm: {
end: "结束通话",
mute: "静音麦克风",
unmute: "取消静音",
- resumePlayback: "启用声音",
+ resumePlayback: "恢复播放",
errorGeneric: "实时语音已停止。请检查服务配置后重试。",
microphoneDenied: "请在浏览器和系统设置中允许麦克风访问,然后重试。",
microphoneUnavailable: "找不到可用的麦克风。请检查所选设备及其连接。",
microphoneBusy: "麦克风正被其他录音占用。请先停止录音,再启动实时语音。",
noProvider: "请在 设置 → 语音 中选择受支持的服务。",
enableInSettings: "请在 设置 → 语音 中启用实时语音。",
- phase: { idle: "关闭", preparing: "正在准备", "acquiring-mic": "等待麦克风", negotiating: "正在协商", connecting: "正在连接", connected: "已连接", reconnecting: "正在重连", closing: "正在结束", ended: "已结束", failed: "已停止" },
+ phase: { idle: "关闭", preparing: "正在准备", "acquiring-mic": "等待麦克风", negotiating: "正在协商", connecting: "连接中…", connected: "已连接", reconnecting: "正在重连", closing: "正在结束…", ended: "已结束", failed: "已停止" },
},
errors: {
HOST_UNAVAILABLE: "本地服务不可用",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index 99a8fad41..c85784729 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -2431,9 +2431,38 @@ sklm: {
liveVoice: {
...en.liveVoice,
title: "即時語音",
+ prepareCall: "準備語音",
+ details: "通話詳細資料",
+ callActionFailed: "無法更新通話。請再試一次或結束通話。",
+ workNotConnected: "此通話未連線至工作階段。",
+ workOptions: "連線至工作階段",
+ allowWork: "允許發起工作請求",
+ noWorkSession: "請選擇或建立本機工作階段。",
+ playbackBlocked: "聲音播放已暫停",
+ playbackFailed: "無法恢復播放,請再試一次。",
+ mediaReleaseUnconfirmed: "無法確認麥克風已釋放。請重新啟動應用程式後再通話。",
+ transcript: "轉錄",
+ transcriptEmpty: "尚無轉錄",
+ userSpeaking: "正在聆聽",
+ assistantSpeaking: "正在說話",
+ muted: "麥克風已靜音",
+ selectWorkSession: "下次通話使用的工作階段",
+ shareContext: "分享有限的近期對話上下文",
+ contextConsent: "啟用後,最多六則近期一般使用者與助理訊息可能會傳送給所選語音服務,用於判斷請求。工具輸出、附件與語音訊息不會分享。此設定僅對下一次通話生效。",
+ contextShared: "本次通話分享了有限的近期對話上下文。",
+ contextNotShared: "本次通話未分享近期對話記錄。",
+ createWorkSession: "建立工作階段",
+ viewWorkSession: "檢視工作階段",
+ viewingDifferentSession: "目前檢視:{{label}}",
+ unknownSession: "其他工作階段",
+ sessionOpenFailed: "無法開啟綁定的工作階段。",
+ sessionCreateFailed: "無法建立工作階段。",
+ microphoneDenied: "請在瀏覽器與系統設定中允許麥克風存取,然後再試一次。",
+ microphoneUnavailable: "找不到可用的麥克風。請檢查所選裝置及其連線。",
+ microphoneBusy: "麥克風正被其他錄音占用。請先停止錄音,再啟動即時語音。",
description: "直接與已設定的即時語音服務交談。啟用前,即時語音會保持關閉。",
enable: "啟用即時語音",
- enableDetail: "麥克風音訊會傳送給你選擇的服務。此功能不會執行 Agent、工具或 MCP 操作。",
+ enableDetail: "麥克風音訊會傳送給你選擇的服務。通話預設僅用於語音交流;發起工作請求需單獨授權並選擇工作階段。",
bindingStatus: "服務狀態",
ready: "就緒",
provider: "服務帳戶",
@@ -2465,11 +2494,11 @@ sklm: {
end: "結束通話",
mute: "麥克風靜音",
unmute: "取消靜音",
- resumePlayback: "啟用聲音",
+ resumePlayback: "恢復播放",
errorGeneric: "即時語音已停止。請檢查服務設定後再試一次。",
noProvider: "請在「設定 → 語音」中選擇支援的服務。",
enableInSettings: "請在「設定 → 語音」中啟用即時語音。",
- phase: { idle: "關閉", preparing: "準備中", "acquiring-mic": "等待麥克風", negotiating: "協商中", connecting: "連線中", connected: "已連線", reconnecting: "重新連線中", closing: "結束中", ended: "已結束", failed: "已停止" },
+ phase: { idle: "關閉", preparing: "準備中", "acquiring-mic": "等待麥克風", negotiating: "協商中", connecting: "連線中…", connected: "已連線", reconnecting: "重新連線中", closing: "正在結束…", ended: "已結束", failed: "已停止" },
},
errors: {
HOST_UNAVAILABLE: "本地服務不可用",
diff --git a/packages/i18n/test/catalogs.test.mjs b/packages/i18n/test/catalogs.test.mjs
index 37c896b0d..c4428dc87 100644
--- a/packages/i18n/test/catalogs.test.mjs
+++ b/packages/i18n/test/catalogs.test.mjs
@@ -31,6 +31,31 @@ test("every shipped catalog matches English keys and interpolation variables", (
}
});
+test("Live Voice preparation and call recovery copy is localized in every shipped catalog", () => {
+ const keys = [
+ "prepareCall", "details", "workOptions", "allowWork", "noWorkSession",
+ "playbackBlocked", "playbackFailed", "mediaReleaseUnconfirmed",
+ "callActionFailed", "workNotConnected", "transcript", "transcriptEmpty",
+ "userSpeaking", "assistantSpeaking", "muted", "resumePlayback",
+ "selectWorkSession", "shareContext", "contextConsent", "contextShared",
+ "contextNotShared", "createWorkSession", "viewWorkSession", "enableDetail",
+ "microphoneDenied", "microphoneUnavailable", "microphoneBusy",
+ "phase.connecting", "phase.closing",
+ ].map((key) => `liveVoice.${key}`);
+
+ for (const [id, catalog] of Object.entries(catalogs)) {
+ const flat = flattenCatalog(catalog);
+ for (const key of keys) {
+ assert.equal(typeof flat[key], "string", `${id} ${key}`);
+ assert.notEqual(flat[key].trim(), "", `${id} ${key}`);
+ if (id !== "en") assert.notEqual(flat[key], english[key], `${id} ${key} must not fall back to English`);
+ }
+ }
+
+ assert.match(english["liveVoice.enableDetail"], /voice-only by default/);
+ assert.match(english["liveVoice.enableDetail"], /separate opt-in and work session/);
+});
+
test("canonical thinking levels are not translated catalog entries", () => {
const levels = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
const effortKeys = [
diff --git a/scripts/test-live-voice-interaction.mjs b/scripts/test-live-voice-interaction.mjs
new file mode 100644
index 000000000..d065372ce
--- /dev/null
+++ b/scripts/test-live-voice-interaction.mjs
@@ -0,0 +1,93 @@
+/** Mounted Live Voice interaction checks, not a full AppShell/provider/device E2E.
+ * Production controls, controller, store, shortcuts and i18n; fake external edges only.
+ */
+import { createRequire } from "node:module";
+import { createServer } from "node:http";
+import { spawn } from "node:child_process";
+import { mkdtemp, readdir, readFile, rm, mkdir } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve, extname } from "node:path";
+import { repositoryRoot, resolveElectronBinary, assertDesktopBuild } from "./e2e/boot.mjs";
+
+const root = repositoryRoot();
+assertDesktopBuild(root);
+const { build } = createRequire(new URL("../packages/agent-runtime/package.json", import.meta.url))("esbuild");
+const temp = await mkdtemp(join(tmpdir(), "pi-live-voice-interaction-"));
+const artifacts = process.env.PI_LIVE_VOICE_ARTIFACT_DIR
+ ? resolve(process.env.PI_LIVE_VOICE_ARTIFACT_DIR)
+ : await mkdtemp(join(tmpdir(), "pi-live-voice-results-"));
+let server;
+try {
+ await mkdir(artifacts, { recursive: true });
+ const assets = join(root, "apps/desktop/out/renderer/assets");
+ const stylesheet = (await readdir(assets)).find((name) => /^index-.*\.css$/.test(name));
+ if (!stylesheet) throw new Error("Built renderer stylesheet missing; reuse the host build environment");
+ await build({
+ entryPoints: [join(root, "apps/desktop/test/fixtures/live-voice-interaction.jsx")],
+ outfile: join(temp, "fixture.js"), bundle: true, format: "esm", platform: "browser", jsx: "automatic",
+ // Reused node_modules may link a primary-checkout dist; test candidate sources.
+ alias: {
+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),
+ "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),
+ "@pi-desktop/voice-runtime/live": join(root, "packages/voice-runtime/src/live/index.ts"),
+ },
+ define: { "import.meta.env.DEV": "false", "process.env.NODE_ENV": '"production"' },
+ plugins: [{
+ name: "live-worklet-url",
+ setup(builder) {
+ // Keep the production URL import without executing a worklet in the WebRTC fixture.
+ builder.onResolve({ filter: /pcm-worklet\.js\?url$/ }, (args) => ({
+ path: args.path, namespace: "live-fixture-url",
+ }));
+ builder.onLoad({ filter: /.*/, namespace: "live-fixture-url" }, () => ({
+ contents: 'export default "/pcm-worklet.js";', loader: "js",
+ }));
+ },
+ }],
+ });
+ server = createServer(async (req, res) => {
+ try {
+ const pathname = new URL(req.url ?? "/", "http://127.0.0.1").pathname;
+ if (pathname === "/") {
+ res.setHeader("content-type", "text/html; charset=utf-8");
+ res.end(`<html lang="en"><head><meta charset="utf-8"><link rel="stylesheet" href="/assets/${stylesheet}"><link rel="stylesheet" href="/fixture.css"></head><body><div id="root"></div><script type="module" src="/fixture.js"></script></body></html>`);
+ return;
+ }
+ let file;
+ if (["/fixture.js", "/fixture.css"].includes(pathname)) file = join(temp, pathname.slice(1));
+ else if (pathname === "/pcm-worklet.js") file = join(root, "apps/desktop/src/features/voice/live/pcm-worklet.js");
+ else if (pathname.startsWith("/assets/")) {
+ file = resolve(assets, decodeURIComponent(pathname.slice("/assets/".length)));
+ if (!file.startsWith(assets + "/") && !file.startsWith(assets + "\\")) file = undefined;
+ }
+ if (!file) { res.writeHead(404); res.end(); return; }
+ res.setHeader("content-type", { ".js": "text/javascript", ".css": "text/css", ".woff2": "font/woff2" }[extname(file)] ?? "application/octet-stream");
+ res.end(await readFile(file));
+ } catch { res.writeHead(404); res.end(); }
+ });
+ await new Promise((resolvePromise, reject) => {
+ server.once("error", reject);
+ server.listen(0, "127.0.0.1", resolvePromise);
+ });
+ const env = {
+ ...process.env,
+ PI_LIVE_VOICE_FIXTURE_URL: `http://127.0.0.1:${server.address().port}`,
+ PI_LIVE_VOICE_ARTIFACT_DIR: artifacts,
+ };
+ delete env.ELECTRON_RUN_AS_NODE;
+ console.log(`Live Voice mounted interaction artifacts: ${artifacts}`);
+ const child = spawn(resolveElectronBinary(root).electronBinary, [
+ `--user-data-dir=${join(temp, "profile")}`,
+ join(root, "apps/desktop/test/fixtures/live-voice-interaction-runner.cjs"),
+ ], { env, windowsHide: true, stdio: "inherit" });
+ process.exitCode = await new Promise((resolvePromise, reject) => {
+ child.once("exit", (code) => resolvePromise(code ?? 1));
+ child.once("error", reject);
+ });
+} finally {
+ if (server?.listening) {
+ server.closeAllConnections();
+ await new Promise((resolvePromise) => server.close(resolvePromise));
+ }
+ await rm(temp, { recursive: true, force: true });
+}