Skip to content

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

feat(voice): add live voice sessions

vastsaef9aae83a74b
diff --git a/apps/desktop/electron/main/bootstrap/shutdown.ts b/apps/desktop/electron/main/bootstrap/shutdown.ts
index fb908837e..cc753a5d5 100644
--- a/apps/desktop/electron/main/bootstrap/shutdown.ts
+++ b/apps/desktop/electron/main/bootstrap/shutdown.ts
@@ -14,6 +14,7 @@ import type { UserMcpRuntime } from "../user-mcp";
import type { McpControlServer } from "../mcp-control";
import type { McpOAuthManager } from "../mcp-oauth";
import { getActiveRemoteHostsBoot, setActiveRemoteHostsBoot } from "./remote-hosts";
+import type { LiveCallService } from "../live-voice/call-service";
const QUIT_TURN_SETTLE_BUDGET_MS = 2_000;
@@ -47,6 +48,7 @@ export type ShutdownDependencies = {
logger: Pick<Logger, "app">;
confirmQuitDialog: () => Promise<boolean>;
disposePowerSaveBlockers: () => void;
+ liveCallService?: Pick<LiveCallService, "endForLifecycle">;
};
/** Register the last-window and before-quit resource lifecycle handlers. */
@@ -69,6 +71,7 @@ export function registerShutdownHandlers({
logger,
confirmQuitDialog,
disposePowerSaveBlockers,
+ liveCallService,
}: ShutdownDependencies): void {
app.on("window-all-closed", () => {
// The D216 tray is resident on every platform, so its presence says nothing
@@ -130,6 +133,7 @@ export function registerShutdownHandlers({
state.toggleWindowAccelerator = null;
}
state.shutdownPromise = (async () => {
+ await liveCallService?.endForLifecycle("app-quit");
// Close every paired remote host before the local host-core so any
// in-flight remote turn's abort still goes over a live socket. Bounded
// parallelism inside `closeAll`; safe to run before local disposals.
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.ts
index a56da6cf6..4db3373bd 100644
--- a/apps/desktop/electron/main/index.ts
+++ b/apps/desktop/electron/main/index.ts
@@ -2,6 +2,8 @@ import {
app,
BrowserWindow,
ipcMain,
+ powerMonitor,
+ session,
} from "electron";
import { join } from "node:path";
import {
@@ -45,6 +47,9 @@ import { applyDevelopmentUserData, desktopDataDir } from "./data-paths";
import { createPlanUiProbe } from "./plan-ui-probe";
import { registerIpcHandlers } from "./ipc/register";
import { createVoiceService } from "./voice-service";
+import { MicrophoneLeaseRegistry } from "./live-voice/microphone-lease";
+import { createLiveCallService } from "./live-voice/runtime";
+import { installLiveMicrophonePermissionHandlers } from "./live-voice/microphone-permissions";
import { MainProcessState } from "./bootstrap/main-state";
import { registerApplicationActivation } from "./bootstrap/app-activation";
import { createHostRuntime } from "./runtime/host";
@@ -817,7 +822,18 @@ runtimeLifecycle = createRuntimeLifecycle({
});
const { bootHostStatus, bootBackends } = runtimeLifecycle;
-const voiceService = createVoiceService(dataDir + "/voice-models", getMainWindow);
+let voiceServiceReference: ReturnType<typeof createVoiceService> | null = null;
+const microphoneLeases = new MicrophoneLeaseRegistry(() => {
+ const phase = voiceServiceReference?.getState().phase;
+ return phase === "preparing" || phase === "starting" || phase === "listening" || phase === "transcribing" || phase === "cancelling";
+});
+const voiceService = createVoiceService(
+ dataDir + "/voice-models",
+ getMainWindow,
+ (token) => microphoneLeases.acquire("dictation", token),
+);
+voiceServiceReference = voiceService;
+const liveCallService = createLiveCallService({ getHost, getMainWindow, vendorOAuth, microphoneLeases });
function registerIpc() {
return registerIpcHandlers({
@@ -914,6 +930,7 @@ function registerIpc() {
isDeveloperMode: () => mainState.developerMode,
sendToRenderer,
voiceService,
+ liveCallService,
});
}
@@ -928,6 +945,36 @@ app.on("web-contents-created", (_event, contents) => {
});
});
+const liveLifecycleWindows = new WeakSet<BrowserWindow>();
+app.on("browser-window-created", (_event, window) => {
+ queueMicrotask(() => {
+ if (getMainWindow() !== window || liveLifecycleWindows.has(window)) return;
+ liveLifecycleWindows.add(window);
+ const contentsId = window.webContents.id;
+ window.on("hide", () => {
+ void liveCallService.endForWebContents(contentsId, "window-hidden");
+ });
+ window.webContents.on("did-start-navigation", (_event, _url, _inPlace, isMainFrame) => {
+ if (isMainFrame) void liveCallService.endForWebContents(contentsId, "window-navigated", true);
+ });
+ window.webContents.once("render-process-gone", () => {
+ void liveCallService.endForWebContents(contentsId, "renderer-gone", true);
+ });
+ window.webContents.once("destroyed", () => {
+ void liveCallService.endForWebContents(contentsId, "renderer-gone", true);
+ });
+ });
+});
+app.once("ready", () => {
+ installLiveMicrophonePermissionHandlers({
+ targetSession: session.defaultSession,
+ getMainWindow,
+ hasReservation: (owner) => liveCallService.hasMicrophoneReservation(owner),
+ });
+ powerMonitor.on("suspend", () => void liveCallService.endForLifecycle("app-suspended"));
+ powerMonitor.on("lock-screen", () => void liveCallService.endForLifecycle("app-suspended"));
+});
+
registerApplicationStartup({
hasSingleInstanceLock,
state: startupState,
@@ -984,6 +1031,7 @@ registerShutdownHandlers({
logger,
confirmQuitDialog,
disposePowerSaveBlockers,
+ liveCallService,
});
registerApplicationActivation({
diff --git a/apps/desktop/electron/main/ipc/live-voice-ipc.ts b/apps/desktop/electron/main/ipc/live-voice-ipc.ts
new file mode 100644
index 000000000..a8863362e
--- /dev/null
+++ b/apps/desktop/electron/main/ipc/live-voice-ipc.ts
@@ -0,0 +1,176 @@
+import type { BrowserWindow, IpcMainInvokeEvent } from "electron";
+import { IPC, type LiveEndReason } from "@pi-desktop/shared";
+import type { LiveCallService as LiveCallServiceImpl, LiveOwner } from "../live-voice/call-service";
+import { liveOwnerFromInvoke } from "../live-voice/owner";
+import type { IpcRegistrar } from "./types";
+
+const END_REASONS = new Set([
+ "user-ended", "user-cancelled-start", "window-hidden", "window-navigated", "renderer-gone",
+ "app-suspended", "app-quit", "provider-invalidated", "disabled", "timeout", "network-error",
+ "protocol-error", "audio-backpressure", "media-release-unconfirmed",
+]);
+
+export function registerLiveVoiceIpc(input: {
+ registrar: IpcRegistrar;
+ service: LiveCallServiceImpl;
+ getMainWindow: () => BrowserWindow | null;
+}): void {
+ const { registrar, service, getMainWindow } = input;
+ const owner = (event: IpcMainInvokeEvent): LiveOwner => {
+ registrar.assertMainWindowSender(event);
+ return liveOwnerFromInvoke(event, getMainWindow());
+ };
+
+ registrar.handleWithEvent(IPC.invoke.liveVoiceStatus, async (event) => {
+ owner(event);
+ return service.status();
+ });
+ registrar.handleWithEvent(IPC.invoke.liveVoicePrepare, async (event, raw: unknown) => {
+ return service.prepare(owner(event), parsePrepare(raw));
+ });
+ registrar.handleWithEvent(IPC.invoke.liveVoiceConnect, async (event, raw: unknown) => {
+ return service.connect(owner(event), parseConnect(raw));
+ });
+ registrar.handleWithEvent(IPC.invoke.liveVoiceSetMuted, async (event, raw: unknown) => {
+ return service.setMuted(owner(event), parseMute(raw));
+ });
+ registrar.handleWithEvent(IPC.invoke.liveVoiceReportMedia, async (event, raw: unknown) => {
+ return service.reportMedia(owner(event), parseMedia(raw));
+ });
+ registrar.handleWithEvent(IPC.invoke.liveVoiceReportPlayback, async (event, raw: unknown) => {
+ service.reportPlayback(owner(event), parsePlayback(raw));
+ return { ok: true };
+ });
+ registrar.handleWithEvent(IPC.invoke.liveVoiceReportDelegation, async (event, raw: unknown) => {
+ return service.reportDelegation(owner(event), parseDelegation(raw));
+ });
+ registrar.handleWithEvent(IPC.invoke.liveVoiceReportControlApplied, async (event, raw: unknown) => {
+ service.reportControlApplied(owner(event), parseControlApplied(raw));
+ return { ok: true };
+ });
+ registrar.handleWithEvent(IPC.invoke.liveVoiceEnd, async (event, raw: unknown) => {
+ return service.end(owner(event), parseEnd(raw));
+ });
+ registrar.handleWithEvent(IPC.invoke.liveVoiceHeartbeat, async (event, raw: unknown) => {
+ const input = record(raw);
+ exactKeys(input, ["callId"]);
+ return service.heartbeat(owner(event), callId(input.callId));
+ });
+}
+
+function parsePrepare(raw: unknown) {
+ const input = record(raw);
+ exactKeys(input, ["requestId", "bindingId", "expectedSettingsRevision", "initialMuted"]);
+ if (typeof input.requestId !== "string" || typeof input.bindingId !== "string" || !input.bindingId.trim() || input.bindingId.length > 256 || !Number.isSafeInteger(input.expectedSettingsRevision) || (input.expectedSettingsRevision as number) < 0 || typeof input.initialMuted !== "boolean") return invalid();
+ return {
+ requestId: input.requestId,
+ bindingId: input.bindingId,
+ expectedSettingsRevision: input.expectedSettingsRevision as number,
+ initialMuted: input.initialMuted,
+ };
+}
+
+function parseConnect(raw: unknown) {
+ const input = record(raw);
+ exactKeys(input, ["callId", "offerSdp"]);
+ const result: { callId: string; offerSdp?: string } = { callId: callId(input.callId) };
+ if (input.offerSdp !== undefined) {
+ if (typeof input.offerSdp !== "string" || Buffer.byteLength(input.offerSdp, "utf8") > 256 * 1024) return invalid();
+ result.offerSdp = input.offerSdp;
+ }
+ return result;
+}
+
+function parseMute(raw: unknown) {
+ const input = record(raw);
+ exactKeys(input, ["callId", "muted", "captureEpoch"]);
+ if (typeof input.muted !== "boolean" || !Number.isSafeInteger(input.captureEpoch) || (input.captureEpoch as number) < 0) return invalid();
+ return { callId: callId(input.callId), muted: input.muted, captureEpoch: input.captureEpoch as number };
+}
+
+function parseMedia(raw: unknown) {
+ const input = record(raw);
+ const kind = input.kind;
+ if (kind === "microphone-active") {
+ exactKeys(input, ["callId", "kind", "active"]);
+ if (typeof input.active !== "boolean") return invalid();
+ return { callId: callId(input.callId), kind, active: input.active } as const;
+ }
+ if (kind === "phase") {
+ exactKeys(input, ["callId", "kind", "phase"]);
+ if (input.phase !== "connecting" && input.phase !== "connected") return invalid();
+ return { callId: callId(input.callId), kind, phase: input.phase } as const;
+ }
+ if (kind === "activity") {
+ exactKeys(input, ["callId", "kind", "userSpeaking", "assistantSpeaking"]);
+ if ((input.userSpeaking !== undefined && typeof input.userSpeaking !== "boolean") || (input.assistantSpeaking !== undefined && typeof input.assistantSpeaking !== "boolean")) return invalid();
+ return { callId: callId(input.callId), kind, ...(input.userSpeaking !== undefined ? { userSpeaking: input.userSpeaking } : {}), ...(input.assistantSpeaking !== undefined ? { assistantSpeaking: input.assistantSpeaking } : {}) } as const;
+ }
+ if (kind === "playback-blocked") {
+ exactKeys(input, ["callId", "kind", "blocked"]);
+ if (typeof input.blocked !== "boolean") return invalid();
+ return { callId: callId(input.callId), kind, blocked: input.blocked } as const;
+ }
+ if (kind === "released") {
+ exactKeys(input, ["callId", "kind"]);
+ return { callId: callId(input.callId), kind } as const;
+ }
+ return invalid();
+}
+
+function parsePlayback(raw: unknown) {
+ const input = record(raw);
+ exactKeys(input, ["callId", "cursors"]);
+ if (!Array.isArray(input.cursors) || input.cursors.length > 64) return invalid();
+ const cursors = input.cursors.map((rawCursor) => {
+ const cursor = record(rawCursor);
+ exactKeys(cursor, ["itemId", "contentIndex", "playedSamples", "sampleRate"]);
+ if (typeof cursor.itemId !== "string" || !cursor.itemId || cursor.itemId.length > 256 || !Number.isSafeInteger(cursor.contentIndex) || (cursor.contentIndex as number) < 0 || !Number.isSafeInteger(cursor.playedSamples) || (cursor.playedSamples as number) < 0 || (cursor.playedSamples as number) > 24_000 * 60 || cursor.sampleRate !== 24_000) return invalid();
+ return { itemId: cursor.itemId, contentIndex: cursor.contentIndex as number, playedSamples: cursor.playedSamples as number, sampleRate: 24_000 as const };
+ });
+ return { callId: callId(input.callId), cursors };
+}
+
+function parseDelegation(raw: unknown) {
+ const input = record(raw);
+ exactKeys(input, ["callId", "delegationId", "instruction"]);
+ if (typeof input.delegationId !== "string" || !input.delegationId.trim() || input.delegationId.length > 256 || typeof input.instruction !== "string" || Buffer.byteLength(input.instruction, "utf8") > 8 * 1024) return invalid();
+ return { callId: callId(input.callId), delegationId: input.delegationId, instruction: input.instruction };
+}
+
+function parseControlApplied(raw: unknown) {
+ const input = record(raw);
+ exactKeys(input, ["callId", "actionId", "applied", "errorCode"]);
+ if (typeof input.actionId !== "string" || !input.actionId || input.actionId.length > 128 || typeof input.applied !== "boolean" || (input.errorCode !== undefined && (typeof input.errorCode !== "string" || input.errorCode.length > 80))) return invalid();
+ return { callId: callId(input.callId), actionId: input.actionId, applied: input.applied, ...(typeof input.errorCode === "string" ? { errorCode: input.errorCode } : {}) };
+}
+
+function parseEnd(raw: unknown) {
+ const input = record(raw);
+ if (typeof input.reason !== "string" || !END_REASONS.has(input.reason)) return invalid();
+ if (input.callId !== undefined) {
+ exactKeys(input, ["callId", "reason"]);
+ return { callId: callId(input.callId), reason: input.reason as LiveEndReason };
+ }
+ exactKeys(input, ["requestId", "reason"]);
+ if (typeof input.requestId !== "string" || !input.requestId || input.requestId.length > 64 || input.reason !== "user-cancelled-start") return invalid();
+ return { requestId: input.requestId, reason: input.reason } as const;
+}
+
+function record(value: unknown): Record<string, unknown> {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();
+ return value as Record<string, unknown>;
+}
+
+function exactKeys(value: Record<string, unknown>, keys: string[]): void {
+ if (Object.keys(value).some((key) => !keys.includes(key))) invalid();
+}
+
+function callId(value: unknown): string {
+ if (typeof value !== "string" || !value.trim() || value.length > 128) return invalid();
+ return value;
+}
+
+function invalid(): never {
+ throw Object.assign(new Error("Live Voice request is invalid"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+}
diff --git a/apps/desktop/electron/main/ipc/provider-ipc.ts b/apps/desktop/electron/main/ipc/provider-ipc.ts
index 6ff132c31..06bf85bee 100644
--- a/apps/desktop/electron/main/ipc/provider-ipc.ts
+++ b/apps/desktop/electron/main/ipc/provider-ipc.ts
@@ -77,6 +77,7 @@ export type ProviderIpcDependencies = {
listRuntimeProviders: () => Promise<RuntimeProvider[]>;
enrichProviderList: (result: { providers: RuntimeProvider[] }) => Promise<unknown>;
bindingForModel: (provider: Pick<RuntimeProvider, "models">, modelId: string) => ModelBinding | undefined;
+ onProviderInvalidated?: (providerId: string) => Promise<void> | void;
};
/** Register provider catalog, model discovery, OAuth and secret channels. */
@@ -90,6 +91,7 @@ export function registerProviderIpc({
listRuntimeProviders,
enrichProviderList,
bindingForModel,
+ onProviderInvalidated,
}: ProviderIpcDependencies): void {
let host: HostProcess | null = null;
const handle = (channel: string, fn: (...args: any[]) => Promise<any>) => {
@@ -173,10 +175,14 @@ export function registerProviderIpc({
});
handle(IPC.invoke.providersUpdate, async (input: unknown) => {
if (!host) throw new Error("host unavailable");
+ const providerId = input && typeof input === "object" && typeof (input as { id?: unknown }).id === "string"
+ ? (input as { id: string }).id
+ : "";
const result = await host.call<{ provider?: RuntimeProvider | null }>(
"providers.update",
input,
);
+ if (providerId) await onProviderInvalidated?.(providerId);
await modelsDevCatalog.ensureLoaded();
return result.provider
? { ...result, provider: enrichProvider(result.provider) }
@@ -190,6 +196,7 @@ export function registerProviderIpc({
"providers.setSecret",
input,
);
+ await onProviderInvalidated?.(input.id);
await modelsDevCatalog.ensureLoaded();
return result.provider
? { ...result, provider: enrichProvider(result.provider) }
@@ -198,7 +205,9 @@ export function registerProviderIpc({
);
handle(IPC.invoke.providersDelete, async (id: string) => {
if (!host) throw new Error("host unavailable");
- return host.call("providers.delete", { id });
+ const result = await host.call("providers.delete", { id });
+ await onProviderInvalidated?.(id);
+ return result;
});
handle(IPC.invoke.providersTest, async (id: string) => {
if (!host) throw new Error("host unavailable");
diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.ts
index 25e96585e..5cd6004cc 100644
--- a/apps/desktop/electron/main/ipc/register.ts
+++ b/apps/desktop/electron/main/ipc/register.ts
@@ -31,6 +31,8 @@ import { createComposerTemplateLoader, registerWorkspaceIpc } from "./workspace-
import { registerComposerIpc } from "./composer-ipc";
import { registerSpeechIpc } from "./speech-ipc";
import { registerVoiceIpc } from "./voice-ipc";
+import { registerLiveVoiceIpc } from "./live-voice-ipc";
+import type { LiveCallService } from "../live-voice/call-service";
import type { IpcRegistrar } from "./types";
import type { createTraySessions } from "../tray-sessions";
import type { createTaskbarUnreadBadge } from "../taskbar-unread-badge";
@@ -55,6 +57,7 @@ export type RegisterIpcDependencies = {
setNotificationViewingSessionId: (sessionId: string | null) => void;
activeUserSubagentDocuments: (...args: any[]) => Promise<any>;
disabledBuiltinSubagents: () => Promise<string[]>;
+ liveCallService?: LiveCallService;
mcpOAuth?: McpOAuthManager;
[name: string]: any;
};
@@ -159,6 +162,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
isDeveloperMode,
sendToRenderer,
voiceService,
+ liveCallService,
} = dependencies;
@@ -269,6 +273,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
applyKeepAwakeWhileRunning,
applyUpdatePreference: (preference) => updater.setPreference(preference),
resolveEffectiveCommandShell,
+ liveCallService,
});
registerConfigSyncIpc({
registrar,
@@ -285,6 +290,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
listRuntimeProviders,
enrichProviderList,
bindingForModel,
+ onProviderInvalidated: (providerId) => liveCallService?.invalidateProvider(providerId),
});
const loadComposerTemplatesCached = createComposerTemplateLoader(logger);
const composerCommandService = registerComposerIpc({
@@ -461,6 +467,9 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {
if (voiceService) {
registerVoiceIpc({ registrar, voiceService });
}
+ if (liveCallService) {
+ registerLiveVoiceIpc({ registrar, service: liveCallService, getMainWindow });
+ }
registerRemoteHostIpc({ registrar });
diff --git a/apps/desktop/electron/main/ipc/settings-ipc.ts b/apps/desktop/electron/main/ipc/settings-ipc.ts
index 2fb6f249d..c43310d78 100644
--- a/apps/desktop/electron/main/ipc/settings-ipc.ts
+++ b/apps/desktop/electron/main/ipc/settings-ipc.ts
@@ -2,6 +2,8 @@ import { IPC, type UpdatePreference } from "@pi-desktop/shared";
import type { AgentSidecar } from "../agent-sidecar";
import type { HostProcess } from "../host-process";
import type { IpcRegistrar } from "./types";
+import type { LiveCallService } from "../live-voice/call-service";
+import type { AppSettings } from "@pi-desktop/shared";
export type SettingsIpcDependencies = {
registrar: IpcRegistrar;
@@ -24,6 +26,7 @@ export type SettingsIpcDependencies = {
applyKeepAwakeWhileRunning: (settings?: { keepAwakeWhileRunning?: unknown } | null) => void;
applyUpdatePreference: (preference: UpdatePreference) => void;
resolveEffectiveCommandShell: () => Promise<unknown>;
+ liveCallService?: Pick<LiveCallService, "beginSettingsWrite" | "settingsWritten">;
};
/** Register app settings and command-shell channels. */
@@ -43,6 +46,7 @@ export function registerSettingsIpc({
applyKeepAwakeWhileRunning,
applyUpdatePreference,
resolveEffectiveCommandShell,
+ liveCallService,
}: SettingsIpcDependencies): void {
let host: HostProcess | null = null;
let sidecar: AgentSidecar | null = null;
@@ -67,7 +71,18 @@ export function registerSettingsIpc({
handle(IPC.invoke.settingsSet, async (settings: unknown) => {
if (!host) throw new Error("host unavailable");
const validatedSettings = validateSettingsWrite(settings);
- const result = await host.call("settings.set", validatedSettings);
+ const currentSettings = await host.call<AppSettings>("settings.get");
+ const prospectiveSettings = validatedSettings && typeof validatedSettings === "object" && !Array.isArray(validatedSettings)
+ ? { ...currentSettings, ...(validatedSettings as Partial<AppSettings>) }
+ : currentSettings;
+ const releaseSettingsWrite = liveCallService?.beginSettingsWrite(prospectiveSettings);
+ let result: AppSettings;
+ try {
+ result = await host.call<AppSettings>("settings.set", validatedSettings);
+ await liveCallService?.settingsWritten(result);
+ } finally {
+ releaseSettingsWrite?.();
+ }
const updatePreference = (validatedSettings as { updatePreference?: unknown })
.updatePreference;
if (updatePreference === "automatic" || updatePreference === "manual") {
diff --git a/apps/desktop/electron/main/live-voice/audio-port.ts b/apps/desktop/electron/main/live-voice/audio-port.ts
new file mode 100644
index 000000000..beab3e40c
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/audio-port.ts
@@ -0,0 +1,285 @@
+import { MessageChannelMain, type MessagePortMain, type WebFrameMain } from "electron";
+import { randomUUID } from "node:crypto";
+import type { LivePlaybackCursor } from "@pi-desktop/shared";
+import { IPC } from "@pi-desktop/shared";
+
+export type LivePcmBridge = {
+ readonly portNonce: string;
+ readonly ready: Promise<void>;
+ setMuted(muted: boolean, captureEpoch: number): Promise<void>;
+ sendOutput(input: { bytes: Uint8Array; playbackEpoch: number; responseId?: string; itemId?: string; contentIndex?: number }): void;
+ reportPlayback(cursors: LivePlaybackCursor[]): void;
+ interrupt(): Promise<LivePlaybackCursor[]>;
+ requestRelease(): Promise<void>;
+ close(): void;
+};
+
+export type LivePcmBridgeOptions = {
+ callId: string;
+ ownerFrame: WebFrameMain;
+ inputSampleRate: 16000 | 24000;
+ outputSampleRate: 24000;
+ onInput: (bytes: Uint8Array, captureEpoch: number) => void;
+ onPlaybackPosition: (cursors: LivePlaybackCursor[]) => void;
+ onReleased: () => void;
+ onFailure: (code: string) => void;
+};
+
+const MAX_INPUT_CREDITS = 10;
+const MAX_OUTPUT_CREDITS = 10;
+const MAX_PORT_FRAME_MS = 100;
+const MAX_INTERRUPTION_ACK_MS = 120;
+const MAX_RELEASE_ACK_MS = 1_000;
+
+export function createLivePcmBridge(options: LivePcmBridgeOptions): LivePcmBridge {
+ const channel = new MessageChannelMain();
+ const port = channel.port1;
+ const portNonce = randomUUID();
+ const maxInputBytes = options.inputSampleRate * 2 * MAX_PORT_FRAME_MS / 1000;
+ const maxOutputBytes = options.outputSampleRate * 2 * MAX_PORT_FRAME_MS / 1000;
+ let closed = false;
+ let readyState: (() => void) | null = null;
+ let readyReject: ((error: Error) => void) | null = null;
+ let muted = true;
+ let captureEpoch = 0;
+ let expectedInputSequence = 1;
+ let nextOutputSequence = 1;
+ let outputCredits = 0;
+ const outstandingOutputCredits = new Map<number, number>();
+ let playbackEpoch = 0;
+ let releaseResolve: (() => void) | null = null;
+ const interruptRequests = new Map<string, { resolve: (cursors: LivePlaybackCursor[]) => void; timer: ReturnType<typeof setTimeout> }>();
+ const mutedWaiters = new Map<number, { resolve: () => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
+ let downlinkSamples = 0;
+ const outputOffsets = new Map<string, number>();
+
+ const ready = new Promise<void>((resolve, reject) => {
+ readyState = resolve;
+ readyReject = reject;
+ });
+
+ function post(data: unknown): void {
+ if (closed) return;
+ port.postMessage(data);
+ }
+
+ function fail(code: string): void {
+ options.onFailure(code);
+ close();
+ }
+
+ function close(): void {
+ if (closed) return;
+ closed = true;
+ readyReject?.(new Error("Live PCM port closed"));
+ readyReject = null;
+ releaseResolve?.();
+ releaseResolve = null;
+ for (const waiter of interruptRequests.values()) {
+ clearTimeout(waiter.timer);
+ waiter.resolve([]);
+ }
+ interruptRequests.clear();
+ for (const waiter of mutedWaiters.values()) {
+ clearTimeout(waiter.timer);
+ waiter.reject(new Error("Live PCM port closed"));
+ }
+ mutedWaiters.clear();
+ outputOffsets.clear();
+ port.removeAllListeners();
+ port.close();
+ channel.port2.close();
+ }
+
+ function handleMessage(raw: unknown): void {
+ if (closed || !raw || typeof raw !== "object" || Array.isArray(raw)) {
+ fail("LIVE_PROTOCOL_ERROR");
+ return;
+ }
+ const message = raw as Record<string, unknown>;
+ if (message.callId !== options.callId || typeof message.kind !== "string") {
+ fail("LIVE_INVALID_OWNER");
+ return;
+ }
+ switch (message.kind) {
+ case "hello":
+ if (readyState === null) return;
+ if (message.nonce !== portNonce) return fail("LIVE_INVALID_OWNER");
+ outputCredits = MAX_OUTPUT_CREDITS;
+ post({ kind: "ready", callId: options.callId, nonce: portNonce, inputCredits: MAX_INPUT_CREDITS, outputSampleRate: options.outputSampleRate });
+ readyState();
+ readyState = null;
+ return;
+ case "input-pcm": {
+ const data = message.pcm16;
+ const sequence = message.sequence;
+ const epoch = message.captureEpoch;
+ if (!(data instanceof ArrayBuffer) || data.byteLength < 2 || data.byteLength > maxInputBytes || data.byteLength % 2 !== 0 || !Number.isSafeInteger(sequence) || sequence !== expectedInputSequence || !Number.isSafeInteger(epoch)) {
+ fail("LIVE_PROTOCOL_ERROR");
+ return;
+ }
+ expectedInputSequence += 1;
+ const accepted = !muted && epoch === captureEpoch;
+ if (accepted) options.onInput(new Uint8Array(data), captureEpoch);
+ post({ kind: "credit", direction: "uplink", consumedSequence: sequence, accepted });
+ return;
+ }
+ case "gate-applied": {
+ const epoch = message.captureEpoch;
+ const value = message.muted;
+ if (!Number.isSafeInteger(epoch) || typeof value !== "boolean" || epoch !== captureEpoch || value !== muted) return;
+ const waiter = mutedWaiters.get(epoch as number);
+ if (!waiter) return;
+ clearTimeout(waiter.timer);
+ mutedWaiters.delete(epoch as number);
+ waiter.resolve();
+ return;
+ }
+ case "credit": {
+ const sequence = message.consumedSequence;
+ if (message.direction !== "downlink" || !Number.isSafeInteger(sequence)) return;
+ const creditedSamples = outstandingOutputCredits.get(sequence as number);
+ if (creditedSamples === undefined) return;
+ outstandingOutputCredits.delete(sequence as number);
+ downlinkSamples = Math.max(0, downlinkSamples - creditedSamples);
+ outputCredits = Math.min(MAX_OUTPUT_CREDITS, outputCredits + 1);
+ return;
+ }
+ case "playback-position": {
+ const cursors = parseCursors(message.cursors);
+ if (!cursors) return fail("LIVE_PROTOCOL_ERROR");
+ options.onPlaybackPosition(cursors);
+ return;
+ }
+ case "interruption-applied": {
+ const id = message.requestId;
+ const cursors = parseCursors(message.cursors);
+ if (typeof id !== "string" || !cursors) return fail("LIVE_PROTOCOL_ERROR");
+ const waiter = interruptRequests.get(id);
+ if (!waiter) return;
+ clearTimeout(waiter.timer);
+ interruptRequests.delete(id);
+ options.onPlaybackPosition(cursors);
+ playbackEpoch = Number.isSafeInteger(message.playbackEpoch) ? message.playbackEpoch as number : playbackEpoch + 1;
+ downlinkSamples = 0;
+ outstandingOutputCredits.clear();
+ outputCredits = MAX_OUTPUT_CREDITS;
+ outputOffsets.clear();
+ post({ kind: "playback-reset", callId: options.callId, playbackEpoch });
+ waiter.resolve(cursors);
+ return;
+ }
+ case "released":
+ options.onReleased();
+ releaseResolve?.();
+ releaseResolve = null;
+ return;
+ default:
+ fail("LIVE_PROTOCOL_ERROR");
+ }
+ }
+
+ port.on("message", (event: { data: unknown }) => handleMessage(event.data));
+ port.start();
+ try {
+ options.ownerFrame.postMessage(IPC.event.liveVoicePort, { callId: options.callId, nonce: portNonce }, [channel.port2]);
+ } catch {
+ close();
+ throw Object.assign(new Error("Live audio port could not be transferred to the owner frame"), { errorCode: "LIVE_INVALID_OWNER" });
+ }
+
+ function setMuted(nextMuted: boolean, nextEpoch: number): Promise<void> {
+ if (closed) return Promise.reject(new Error("Live PCM port closed"));
+ if (!Number.isSafeInteger(nextEpoch) || nextEpoch < captureEpoch || (nextEpoch === captureEpoch && muted !== nextMuted)) {
+ return Promise.reject(Object.assign(new Error("Live capture epoch is stale"), { errorCode: "LIVE_STALE_CALL" }));
+ }
+ captureEpoch = nextEpoch;
+ muted = nextMuted;
+ return new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ mutedWaiters.delete(nextEpoch);
+ reject(Object.assign(new Error("Live capture gate acknowledgement timed out"), { errorCode: "LIVE_TIMEOUT" }));
+ }, 1_000);
+ mutedWaiters.set(nextEpoch, { resolve, reject, timer });
+ post({ kind: "set-gate", callId: options.callId, muted: nextMuted, captureEpoch: nextEpoch });
+ });
+ }
+
+ function sendOutput(input: { bytes: Uint8Array; playbackEpoch: number; responseId?: string; itemId?: string; contentIndex?: number }): void {
+ if (closed) return;
+ if (input.bytes.byteLength === 0 || input.bytes.byteLength % 2 !== 0) return fail("LIVE_PROTOCOL_ERROR");
+ const key = `${input.responseId ?? ""}:${input.itemId ?? ""}:${input.contentIndex ?? 0}`;
+ if (input.itemId && outputOffsets.size >= 256 && !outputOffsets.has(key)) return fail("LIVE_AUDIO_BACKPRESSURE");
+ let offset = outputOffsets.get(key) ?? 0;
+ for (let start = 0; start < input.bytes.length; start += maxOutputBytes) {
+ const end = Math.min(input.bytes.length, start + maxOutputBytes);
+ if (outputCredits <= 0 || downlinkSamples + (end - start) / 2 > options.outputSampleRate) return fail("LIVE_AUDIO_BACKPRESSURE");
+ const data = input.bytes.slice(start, end);
+ const buffer = data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) as ArrayBuffer;
+ const sequence = nextOutputSequence++;
+ outputCredits -= 1;
+ outstandingOutputCredits.set(sequence, data.byteLength / 2);
+ downlinkSamples += data.byteLength / 2;
+ post({
+ kind: "output-pcm",
+ callId: options.callId,
+ sequence,
+ playbackEpoch: input.playbackEpoch,
+ responseKey: key,
+ itemId: input.itemId,
+ contentIndex: input.contentIndex ?? 0,
+ sampleOffset: offset,
+ pcm16: buffer,
+ });
+ offset += data.byteLength / 2;
+ }
+ outputOffsets.set(key, offset);
+ }
+
+ function reportPlayback(cursors: LivePlaybackCursor[]): void {
+ if (closed) return;
+ if (cursors.length > 64 || cursors.some((cursor) => cursor.sampleRate !== options.outputSampleRate || !Number.isSafeInteger(cursor.playedSamples) || cursor.playedSamples < 0)) {
+ return fail("LIVE_PROTOCOL_ERROR");
+ }
+ options.onPlaybackPosition(cursors);
+ }
+
+ function interrupt(): Promise<LivePlaybackCursor[]> {
+ if (closed) return Promise.reject(new Error("Live PCM port closed"));
+ const requestId = randomUUID();
+ return new Promise<LivePlaybackCursor[]>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ interruptRequests.delete(requestId);
+ reject(Object.assign(new Error("Live playback did not confirm interruption"), { errorCode: "LIVE_TIMEOUT" }));
+ }, MAX_INTERRUPTION_ACK_MS);
+ interruptRequests.set(requestId, { resolve, timer });
+ post({ kind: "interrupt", callId: options.callId, requestId, playbackEpoch: playbackEpoch + 1 });
+ });
+ }
+
+ function requestRelease(): Promise<void> {
+ if (closed) return Promise.resolve();
+ return new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ releaseResolve = null;
+ reject(Object.assign(new Error("Live microphone release was not confirmed"), { errorCode: "LIVE_MEDIA_RELEASE_UNCONFIRMED" }));
+ }, MAX_RELEASE_ACK_MS);
+ releaseResolve = () => { clearTimeout(timer); resolve(); };
+ post({ kind: "release", callId: options.callId });
+ });
+ }
+
+ return { portNonce, ready, setMuted, sendOutput, reportPlayback, interrupt, requestRelease, close };
+}
+
+function parseCursors(value: unknown): LivePlaybackCursor[] | null {
+ if (!Array.isArray(value) || value.length > 64) return null;
+ const result: LivePlaybackCursor[] = [];
+ for (const raw of value) {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const item = raw as Record<string, unknown>;
+ if (typeof item.itemId !== "string" || item.itemId.length > 256 || !Number.isSafeInteger(item.contentIndex) || !Number.isSafeInteger(item.playedSamples) || (item.playedSamples as number) < 0 || item.sampleRate !== 24000) return null;
+ result.push({ itemId: item.itemId, contentIndex: item.contentIndex as number, playedSamples: item.playedSamples as number, sampleRate: 24000 });
+ }
+ return result;
+}
diff --git a/apps/desktop/electron/main/live-voice/auth-resolver.ts b/apps/desktop/electron/main/live-voice/auth-resolver.ts
new file mode 100644
index 000000000..bc6e68bc7
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/auth-resolver.ts
@@ -0,0 +1,122 @@
+import { Buffer } from "node:buffer";
+import { OAUTH_AUTH_KIND, type LiveBinding, type ProviderPublic } from "@pi-desktop/shared";
+import type { VendorOAuth } from "../oauth";
+import type { LiveResolvedAuth } from "./types";
+
+export type LiveAuthResolverDeps = {
+ callHost: <T>(method: string, params?: unknown) => Promise<T>;
+ vendorOAuth: Pick<VendorOAuth, "resolveAuth">;
+};
+
+export type LiveProviderRecord = {
+ provider: ProviderPublic;
+ secret?: string;
+};
+
+export function codexAccountIdFromJwt(accessToken: string): string | null {
+ if (accessToken.length > 16_384) return null;
+ const parts = accessToken.split(".");
+ if (parts.length !== 3 || !parts[1] || parts[1].length > 12_000) return null;
+ try {
+ const decoded: unknown = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
+ if (!decoded || typeof decoded !== "object" || Array.isArray(decoded)) return null;
+ const claim = (decoded as Record<string, unknown>)["https://api.openai.com/auth"];
+ if (!claim || typeof claim !== "object" || Array.isArray(claim)) return null;
+ const accountId = (claim as Record<string, unknown>).chatgpt_account_id;
+ return typeof accountId === "string" && accountId.length > 0 && accountId.length <= 256 ? accountId : null;
+ } catch {
+ return null;
+ }
+}
+
+function headerValue(headers: Record<string, unknown> | undefined, name: string): string | null {
+ if (!headers) return null;
+ const value = Object.entries(headers).find(([key]) => key.toLowerCase() === name.toLowerCase())?.[1];
+ return typeof value === "string" && value.trim() ? value.trim() : null;
+}
+
+function bearerToken(value: string | undefined): string | null {
+ if (!value?.trim()) return null;
+ const match = value.trim().match(/^Bearer\s+(.+)$/i);
+ return (match?.[1] ?? value).trim() || null;
+}
+
+export function resolveCodexRequestAuth(auth: {
+ apiKey?: string;
+ headers?: Record<string, unknown>;
+}): { accessToken: string; accountId: string } {
+ const fromApiKey = bearerToken(auth.apiKey);
+ const fromHeader = bearerToken(headerValue(auth.headers, "authorization") ?? undefined);
+ if (fromApiKey && fromHeader && fromApiKey !== fromHeader) {
+ throw Object.assign(new Error("Codex authentication sources disagree"), { errorCode: "LIVE_AUTH_REQUIRED" });
+ }
+ const accessToken = fromApiKey ?? fromHeader;
+ if (!accessToken) throw Object.assign(new Error("Codex account credentials are unavailable"), { errorCode: "LIVE_AUTH_REQUIRED" });
+
+ const headerAccountId = headerValue(auth.headers, "chatgpt-account-id");
+ const tokenAccountId = codexAccountIdFromJwt(accessToken);
+ if (headerAccountId && tokenAccountId && headerAccountId !== tokenAccountId) {
+ throw Object.assign(new Error("Codex account metadata is inconsistent"), { errorCode: "LIVE_ACCOUNT_ID_MISSING" });
+ }
+ const accountId = headerAccountId ?? tokenAccountId;
+ if (!accountId) throw Object.assign(new Error("Codex account metadata is unavailable"), { errorCode: "LIVE_ACCOUNT_ID_MISSING" });
+ return { accessToken, accountId };
+}
+
+export class LiveAuthResolver {
+ constructor(private readonly deps: LiveAuthResolverDeps) {}
+
+ async provider(providerId: string): Promise<LiveProviderRecord | null> {
+ const result = await this.deps.callHost<{ provider?: ProviderPublic }>("providers.get", { id: providerId });
+ return result.provider ? { provider: result.provider } : null;
+ }
+
+ async resolve(binding: LiveBinding): Promise<{ provider: ProviderPublic; auth: LiveResolvedAuth }> {
+ const initial = await this.provider(binding.providerId);
+ if (!initial?.provider || !initial.provider.enabled) {
+ throw Object.assign(new Error("The selected Provider is unavailable"), { errorCode: "LIVE_PROVIDER_NOT_FOUND" });
+ }
+ const provider = initial.provider;
+ if (binding.adapterId === "codex-live") {
+ if (provider.authKind !== OAUTH_AUTH_KIND || provider.vendorKey !== "openai-codex") {
+ throw Object.assign(new Error("Codex Live requires a signed-in Codex account"), { errorCode: "LIVE_AUTH_KIND_UNSUPPORTED" });
+ }
+ let requestAuth: { accessToken: string; accountId: string };
+ try {
+ requestAuth = resolveCodexRequestAuth(await this.deps.vendorOAuth.resolveAuth(binding.providerId));
+ } catch (error) {
+ if (error && typeof error === "object" && "errorCode" in error) throw error;
+ throw Object.assign(new Error("Codex account credentials could not be resolved"), { errorCode: "LIVE_AUTH_REQUIRED", cause: error });
+ }
+ await this.assertStillSelected(binding, provider);
+ return { provider, auth: { kind: "codex-oauth", ...requestAuth } };
+ }
+
+ if (provider.authKind === OAUTH_AUTH_KIND) {
+ throw Object.assign(new Error("Live API-key adapters do not accept OAuth credentials"), { errorCode: "LIVE_AUTH_KIND_UNSUPPORTED" });
+ }
+ if (!provider.hasSecret) throw Object.assign(new Error("The selected Provider has no API key"), { errorCode: "LIVE_AUTH_REQUIRED" });
+ if (binding.adapterId === "gemini-live" && (provider.vendorKey !== "google" || provider.apiStyle !== "google_generative_ai")) {
+ throw Object.assign(new Error("Gemini Live requires a Google Generative AI API-key Provider"), { errorCode: "LIVE_AUTH_KIND_UNSUPPORTED" });
+ }
+ const secret = await this.deps.callHost<{ value?: string }>("providers.getSecret", { id: binding.providerId });
+ const apiKey = typeof secret.value === "string" ? secret.value.trim() : "";
+ if (!apiKey) throw Object.assign(new Error("The selected Provider API key is missing"), { errorCode: "LIVE_AUTH_REQUIRED" });
+ await this.assertStillSelected(binding, provider);
+ const baseUrl = provider.baseUrl?.trim() ?? "";
+ if (binding.adapterId === "openai-realtime" && !baseUrl) {
+ throw Object.assign(new Error("The selected Provider has no endpoint URL"), { errorCode: "LIVE_PROVIDER_NOT_FOUND" });
+ }
+ return { provider, auth: { kind: "api-key", apiKey, baseUrl } };
+ }
+
+ private async assertStillSelected(binding: LiveBinding, original: ProviderPublic): Promise<void> {
+ const current = await this.provider(binding.providerId);
+ if (!current?.provider?.enabled || current.provider.id !== original.id || current.provider.authKind !== original.authKind || current.provider.vendorKey !== original.vendorKey) {
+ throw Object.assign(new Error("The selected Provider changed during authentication"), { errorCode: "LIVE_PROVIDER_NOT_FOUND" });
+ }
+ if (binding.adapterId === "openai-realtime" && current.provider.baseUrl !== original.baseUrl) {
+ throw Object.assign(new Error("The selected Provider endpoint changed during authentication"), { errorCode: "LIVE_PROVIDER_NOT_FOUND" });
+ }
+ }
+}
diff --git a/apps/desktop/electron/main/live-voice/call-service.ts b/apps/desktop/electron/main/live-voice/call-service.ts
new file mode 100644
index 000000000..d480a3704
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/call-service.ts
@@ -0,0 +1,899 @@
+import { randomUUID } from "node:crypto";
+import { Buffer } from "node:buffer";
+import {
+ ErrorCodes,
+ OAUTH_AUTH_KIND,
+ type AppSettings,
+ type LiveBinding,
+ type LiveBindingReadiness,
+ type LiveCallView,
+ type LiveConnectRequest,
+ type LiveControlEvent,
+ type LiveDelegationRequest,
+ type LiveEndReason,
+ type LiveEndRequest,
+ type LiveMediaReport,
+ type LivePhase,
+ type LivePlaybackCursor,
+ type LivePrepareRequest,
+ type LivePreparedCall,
+ type LiveStatus,
+ type LiveTranscriptEvent,
+ type LiveVoiceSettings,
+ validateLiveVoiceSettings,
+} from "@pi-desktop/shared";
+import type { LiveWireEvent } from "@pi-desktop/voice-runtime/live";
+import { LiveAuthResolver } from "./auth-resolver";
+import type { LivePcmBridge } from "./audio-port";
+import type { LiveAdapter, LiveAdapterContext, LiveResolvedAuth } from "./types";
+
+export type LiveOwner = {
+ webContentsId: number;
+ frameProcessId: number;
+ frameRoutingId: number;
+ url: string;
+};
+
+export type LiveCallServiceDeps = {
+ loadSettings: () => Promise<AppSettings>;
+ authResolver: LiveAuthResolver;
+ createAdapter: (context: LiveAdapterContext) => LiveAdapter;
+ createPcmBridge: (input: {
+ callId: string;
+ owner: LiveOwner;
+ inputSampleRate: 16000 | 24000;
+ outputSampleRate: 24000;
+ onInput: (bytes: Uint8Array, captureEpoch: number) => void;
+ onPlaybackPosition: (cursors: LivePlaybackCursor[]) => void;
+ onReleased: () => void;
+ onFailure: (code: string) => void;
+ }) => LivePcmBridge;
+ sendView: (owner: LiveOwner, view: LiveCallView) => void;
+ sendControl: (owner: LiveOwner, event: LiveControlEvent) => void;
+ sendTranscript: (owner: LiveOwner, event: LiveTranscriptEvent) => void;
+ ownerAlive: (owner: LiveOwner) => boolean;
+ acquireMicrophone: (callId: string) => () => void;
+ acquireBackgroundThrottlingLease?: (callId: string) => () => void;
+ now?: () => number;
+};
+
+type Slot = {
+ callId: string;
+ requestId: string;
+ requestedBindingId: string;
+ owner: LiveOwner;
+ binding: LiveBinding | null;
+ settingsRevision: number;
+ phase: LivePhase;
+ revision: number;
+ abort: AbortController;
+ desiredMuted: boolean;
+ muted: boolean;
+ captureEpoch: number;
+ playbackEpoch: number;
+ microphoneActive: boolean;
+ mediaRelease: "pending" | "confirmed" | "unconfirmed";
+ mediaReleased: Promise<void>;
+ resolveMediaReleased: (() => void) | null;
+ connectedAt?: string;
+ playbackBlocked?: boolean;
+ userSpeaking: boolean;
+ assistantSpeaking: boolean;
+ error?: { code: string; stage?: string; retriable: boolean };
+ notice?: { code: string; retriable: boolean };
+ adapter: LiveAdapter | null;
+ bridge: LivePcmBridge | null;
+ releaseMicrophone: (() => void) | null;
+ releaseBackgroundLease: (() => void) | null;
+ heartbeatAt: number;
+ maxDurationTimer?: ReturnType<typeof setTimeout>;
+ heartbeatTimer?: ReturnType<typeof setTimeout>;
+ reservationTimer?: ReturnType<typeof setTimeout>;
+ connectPromise?: Promise<{ answerSdp?: string; revision: number }>;
+ connectFingerprint?: string;
+ delegationInstructions: Map<string, string>;
+ pendingControls: Map<string, { timer: ReturnType<typeof setTimeout> }>;
+ transcriptLengths: Map<string, number>;
+};
+
+type RequestEntry = { fingerprint: string; promise: Promise<LivePreparedCall> };
+type SettingsSnapshot = { value: LiveVoiceSettings; fingerprint: string; revision: number; invalid: boolean };
+
+const MAX_CALLS_PER_OWNER_REQUEST_CACHE = 64;
+const MAX_DELEGATIONS_PER_CALL = 256;
+const MAX_TRANSCRIPT_SEGMENTS = 200;
+const MAX_TRANSCRIPT_BYTES = 64 * 1024;
+const MAX_INSTRUCTION_BYTES = 8 * 1024;
+const PREPARE_DEADLINE_MS = 5_000;
+const RESERVATION_TIMEOUT_MS = 60_000;
+const AUTH_TIMEOUT_MS = 15_000;
+const CONNECT_TIMEOUT_MS = 15_000;
+const TOTAL_CONNECT_TIMEOUT_MS = 40_000;
+const OWNER_LEASE_MS = 20_000;
+const OWNER_HEARTBEAT_MS = 5_000;
+const MAX_CALL_MS = 30 * 60_000;
+const REJECTION_ACK_TIMEOUT_MS = 1_000;
+
+function ownerKey(owner: LiveOwner): string {
+ return `${owner.webContentsId}:${owner.frameProcessId}:${owner.frameRoutingId}`;
+}
+
+function fingerprint(value: unknown): string {
+ return JSON.stringify(value);
+}
+
+function liveVoiceFromSettings(settings: unknown): { value: LiveVoiceSettings; invalid: boolean } {
+ if (!settings || typeof settings !== "object" || Array.isArray(settings)) return { value: { enabled: false, bindings: [] }, invalid: true };
+ const raw = (settings as { liveVoice?: unknown }).liveVoice;
+ if (raw === undefined) return { value: { enabled: false, bindings: [] }, invalid: false };
+ try {
+ return { value: validateLiveVoiceSettings(raw), invalid: false };
+ } catch {
+ return { value: { enabled: false, bindings: [] }, invalid: true };
+ }
+}
+
+function transition(slot: Slot, next: LivePhase): void {
+ const allowed: Record<LivePhase, readonly LivePhase[]> = {
+ idle: ["preparing"],
+ preparing: ["acquiring-mic", "closing", "failed"],
+ "acquiring-mic": ["negotiating", "connecting", "closing", "failed"],
+ negotiating: ["connecting", "closing", "failed"],
+ connecting: ["connected", "closing", "failed"],
+ connected: ["reconnecting", "closing", "failed"],
+ reconnecting: ["connected", "closing", "failed"],
+ closing: ["ended", "failed"],
+ ended: [],
+ failed: [],
+ };
+ if (slot.phase !== next && !allowed[slot.phase].includes(next)) {
+ throw Object.assign(new Error("Live call state transition is invalid"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ }
+ slot.phase = next;
+}
+
+function errorCode(error: unknown, fallback = "LIVE_NETWORK_ERROR"): { code: string; retriable: boolean } {
+ const value = error && typeof error === "object" ? error as { errorCode?: unknown; retriable?: unknown } : null;
+ const allowed = new Set<string>([
+ "LIVE_DISABLED", "LIVE_NOT_CONFIGURED", "LIVE_PROVIDER_NOT_FOUND", "LIVE_AUTH_KIND_UNSUPPORTED", "LIVE_AUTH_REQUIRED",
+ "LIVE_ACCOUNT_ID_MISSING", "LIVE_ACCESS_DENIED", "LIVE_RATE_LIMITED", "LIVE_PROTOCOL_UNSUPPORTED", "LIVE_PROTOCOL_ERROR",
+ "LIVE_ALREADY_ACTIVE", "LIVE_REQUEST_CONFLICT", "LIVE_SETTINGS_IN_USE", "LIVE_MEDIA_RELEASE_UNCONFIRMED", "LIVE_STALE_CALL",
+ "LIVE_INVALID_OWNER", "LIVE_MICROPHONE_BUSY", "LIVE_MICROPHONE_DENIED", "LIVE_MICROPHONE_UNAVAILABLE", "LIVE_MEDIA_UNSUPPORTED",
+ "LIVE_PLAYBACK_BLOCKED", "LIVE_TIMEOUT", "LIVE_NETWORK_ERROR", "LIVE_NETWORK_POLICY_UNSUPPORTED", "LIVE_AUDIO_BACKPRESSURE",
+ "LIVE_EXECUTION_NOT_CONNECTED",
+ ]);
+ const code = typeof value?.errorCode === "string" && allowed.has(value.errorCode) ? value.errorCode : fallback;
+ return { code, retriable: typeof value?.retriable === "boolean" ? value.retriable : ["LIVE_TIMEOUT", "LIVE_NETWORK_ERROR", "LIVE_RATE_LIMITED"].includes(code) };
+}
+
+export class LiveCallService {
+ private current: Slot | null = null;
+ private terminal: LiveCallView | null = null;
+ private quarantine: { owner: LiveOwner; releaseMicrophone: (() => void) | null } | null = null;
+ private readonly requests = new Map<string, RequestEntry>();
+ private readonly cancellationTombstones = new Map<string, number>();
+ private settingsSnapshot: SettingsSnapshot | null = null;
+ private settingsWritePending = false;
+ private readonly deps: LiveCallServiceDeps;
+ private readonly now: () => number;
+
+ constructor(deps: LiveCallServiceDeps) {
+ this.deps = deps;
+ this.now = deps.now ?? Date.now;
+ }
+
+ async status(): Promise<LiveStatus> {
+ const snapshot = await this.readSettings();
+ const bindings: LiveBindingReadiness[] = [];
+ for (const binding of snapshot.value.bindings) {
+ let item: LiveBindingReadiness = {
+ bindingId: binding.id,
+ adapterId: binding.adapterId,
+ configured: true,
+ credentialsPresent: false,
+ selectable: false,
+ };
+ try {
+ const record = await this.deps.authResolver.provider(binding.providerId);
+ if (!record?.provider) item = { ...item, reason: "missing-provider" };
+ else {
+ item = { ...item, providerLabel: `${record.provider.name} · ${record.provider.id.slice(-6)}` };
+ if (!record.provider.enabled) item = { ...item, reason: "disabled" };
+ else if (!this.providerMatches(binding, record.provider)) item = { ...item, reason: "wrong-auth-kind" };
+ else if (!record.provider.hasSecret) item = { ...item, reason: "missing-credentials" };
+ else item = { ...item, credentialsPresent: true, selectable: snapshot.value.enabled && !snapshot.invalid, ...(snapshot.value.enabled ? {} : { reason: "disabled" }) };
+ }
+ } catch {
+ item = { ...item, reason: "missing-provider" };
+ }
+ if (snapshot.invalid) item = { ...item, selectable: false, reason: "invalid-settings" };
+ bindings.push(item);
+ }
+ return {
+ enabled: snapshot.value.enabled && !snapshot.invalid,
+ settingsRevision: snapshot.revision,
+ ...(snapshot.value.selectedBindingId ? { selectedBindingId: snapshot.value.selectedBindingId } : {}),
+ bindings,
+ call: this.current ? this.toView(this.current) : this.terminal,
+ };
+ }
+
+ hasMicrophoneReservation(owner: LiveOwner): boolean {
+ const slot = this.current;
+ return Boolean(
+ slot &&
+ ownerKey(slot.owner) === ownerKey(owner) &&
+ slot.releaseMicrophone &&
+ ["preparing", "acquiring-mic", "negotiating", "connecting", "connected", "reconnecting"].includes(slot.phase),
+ );
+ }
+
+ prepare(owner: LiveOwner, request: LivePrepareRequest): Promise<LivePreparedCall> {
+ validatePrepareRequest(request);
+ const key = `${ownerKey(owner)}:${request.requestId}`;
+ const requestFingerprint = fingerprint(request);
+ const existing = this.requests.get(key);
+ if (existing) {
+ if (existing.fingerprint !== requestFingerprint) return Promise.reject(liveError("LIVE_REQUEST_CONFLICT"));
+ return existing.promise;
+ }
+ this.pruneTombstones();
+ if (this.cancellationTombstones.has(key)) return Promise.reject(liveError("LIVE_STALE_CALL"));
+ if (this.current || this.quarantine) return Promise.reject(liveError(this.quarantine ? "LIVE_MEDIA_RELEASE_UNCONFIRMED" : "LIVE_ALREADY_ACTIVE"));
+ if (this.settingsWritePending) return Promise.reject(liveError("LIVE_SETTINGS_IN_USE"));
+
+ const slot = this.makeSlot(owner, request);
+ try {
+ // Reserve the process-wide capture lease synchronously with prepare so
+ // Dictation cannot begin while the renderer is opening its permission UI.
+ slot.releaseMicrophone = this.deps.acquireMicrophone(slot.callId);
+ } catch (error) {
+ return Promise.reject(error);
+ }
+ this.current = slot;
+ this.terminal = null;
+ const promise = Promise.resolve().then(() => this.runPrepare(slot, request)).catch(async (error: unknown) => {
+ await this.failAndCleanup(slot, error, "prepare");
+ throw error;
+ });
+ this.requests.set(key, { fingerprint: requestFingerprint, promise });
+ this.trimRequests();
+ this.publish(slot);
+ return promise;
+ }
+
+ async connect(owner: LiveOwner, request: LiveConnectRequest): Promise<{ answerSdp?: string; revision: number }> {
+ const slot = this.requireCurrent(owner, request.callId);
+ const offeredSdp = request.offerSdp;
+ if (slot.binding?.adapterId === "codex-live") {
+ if (typeof offeredSdp !== "string" || Buffer.byteLength(offeredSdp, "utf8") > 256 * 1024) throw liveError("LIVE_PROTOCOL_ERROR");
+ } else if (offeredSdp !== undefined) throw liveError("LIVE_PROTOCOL_ERROR");
+ const connectFingerprint = fingerprint({ callId: request.callId, offerSdp: offeredSdp ?? null });
+ if (slot.connectPromise) {
+ if (slot.connectFingerprint !== connectFingerprint) throw liveError("LIVE_REQUEST_CONFLICT");
+ return slot.connectPromise;
+ }
+ slot.connectFingerprint = connectFingerprint;
+ slot.connectPromise = this.runConnect(slot, offeredSdp).catch(async (error: unknown) => {
+ await this.failAndCleanup(slot, error, "handshake");
+ throw error;
+ });
+ return slot.connectPromise;
+ }
+
+ async setMuted(owner: LiveOwner, request: { callId: string; muted: boolean; captureEpoch: number }): Promise<LiveCallView> {
+ const slot = this.requireCurrent(owner, request.callId, true);
+ if (typeof request.muted !== "boolean" || !Number.isSafeInteger(request.captureEpoch) || request.captureEpoch <= slot.captureEpoch) throw liveError("LIVE_STALE_CALL");
+ if (!request.muted && slot.phase !== "connected") throw liveError("LIVE_STALE_CALL");
+ slot.captureEpoch = request.captureEpoch;
+ slot.muted = request.muted;
+ slot.desiredMuted = request.muted;
+ this.publish(slot);
+ try {
+ if (slot.bridge) await slot.bridge.setMuted(request.muted, request.captureEpoch);
+ if (slot.adapter?.setInputMuted) await slot.adapter.setInputMuted(request.muted);
+ this.assertCurrent(slot);
+ return this.toView(slot);
+ } catch (error) {
+ if (!request.muted) {
+ slot.muted = true;
+ slot.desiredMuted = true;
+ this.publish(slot);
+ }
+ throw error;
+ }
+ }
+
+ reportMedia(owner: LiveOwner, report: LiveMediaReport): LiveCallView {
+ const slot = this.requireCurrent(owner, report.callId, report.kind === "released");
+ switch (report.kind) {
+ case "microphone-active":
+ slot.microphoneActive = report.active;
+ slot.mediaRelease = report.active ? "pending" : slot.mediaRelease;
+ break;
+ case "phase":
+ if (report.phase === "connected") {
+ if (!slot.adapter || slot.phase === "closing" || slot.phase === "failed") throw liveError("LIVE_STALE_CALL");
+ if (slot.phase !== "connected") transition(slot, "connected");
+ slot.connectedAt ??= new Date(this.now()).toISOString();
+ slot.mediaRelease = slot.microphoneActive ? "pending" : slot.mediaRelease;
+ this.startCallTimers(slot);
+ } else if (slot.phase === "acquiring-mic" || slot.phase === "negotiating") {
+ transition(slot, "connecting");
+ }
+ break;
+ case "activity":
+ if (report.userSpeaking !== undefined) slot.userSpeaking = report.userSpeaking;
+ if (report.assistantSpeaking !== undefined) slot.assistantSpeaking = report.assistantSpeaking;
+ break;
+ case "playback-blocked":
+ slot.playbackBlocked = report.blocked;
+ if (report.blocked) slot.notice = { code: "LIVE_PLAYBACK_BLOCKED", retriable: true };
+ break;
+ case "released":
+ slot.microphoneActive = false;
+ slot.mediaRelease = "confirmed";
+ slot.resolveMediaReleased?.();
+ slot.resolveMediaReleased = null;
+ break;
+ }
+ this.publish(slot);
+ return this.toView(slot);
+ }
+
+ reportPlayback(owner: LiveOwner, input: { callId: string; cursors: LivePlaybackCursor[] }): void {
+ const slot = this.requireCurrent(owner, input.callId);
+ if (!Array.isArray(input.cursors) || input.cursors.length > 64) throw liveError("LIVE_PROTOCOL_ERROR");
+ slot.bridge?.reportPlayback(input.cursors);
+ }
+
+ async reportDelegation(owner: LiveOwner, request: LiveDelegationRequest): Promise<{ accepted: boolean }> {
+ const slot = this.requireCurrent(owner, request.callId);
+ if (slot.binding?.adapterId !== "codex-live" || typeof request.delegationId !== "string" || !request.delegationId.trim() || request.delegationId.length > 256 || typeof request.instruction !== "string" || Buffer.byteLength(request.instruction, "utf8") > MAX_INSTRUCTION_BYTES) {
+ throw liveError("LIVE_PROTOCOL_ERROR");
+ }
+ const id = request.delegationId.trim();
+ const prior = slot.delegationInstructions.get(id);
+ if (prior !== undefined) {
+ if (prior !== request.instruction) throw liveError("LIVE_PROTOCOL_ERROR");
+ return { accepted: true };
+ }
+ if (slot.delegationInstructions.size >= MAX_DELEGATIONS_PER_CALL) throw liveError("LIVE_PROTOCOL_ERROR");
+ slot.delegationInstructions.set(id, request.instruction);
+ const actionId = randomUUID();
+ const timer = setTimeout(() => {
+ const current = this.current;
+ if (current !== slot || !slot.pendingControls.has(actionId)) return;
+ slot.pendingControls.delete(actionId);
+ slot.notice = { code: "LIVE_EXECUTION_NOT_CONNECTED", retriable: false };
+ void this.failAndCleanup(slot, liveError("LIVE_PROTOCOL_ERROR"), "control");
+ }, REJECTION_ACK_TIMEOUT_MS);
+ slot.pendingControls.set(actionId, { timer });
+ this.deps.sendControl(owner, { callId: slot.callId, kind: "reject-delegation", actionId, delegationId: id, reason: "EXECUTION_NOT_CONNECTED" });
+ this.publish(slot);
+ return { accepted: true };
+ }
+
+ reportControlApplied(owner: LiveOwner, input: { callId: string; actionId: string; applied: boolean; errorCode?: string }): void {
+ const slot = this.requireCurrent(owner, input.callId);
+ if (typeof input.actionId !== "string" || typeof input.applied !== "boolean") throw liveError("LIVE_PROTOCOL_ERROR");
+ const pending = slot.pendingControls.get(input.actionId);
+ if (!pending) return;
+ clearTimeout(pending.timer);
+ slot.pendingControls.delete(input.actionId);
+ if (!input.applied) {
+ slot.notice = { code: "LIVE_EXECUTION_NOT_CONNECTED", retriable: false };
+ this.publish(slot);
+ void this.failAndCleanup(slot, liveError("LIVE_PROTOCOL_ERROR"), "control");
+ }
+ }
+
+ async end(owner: LiveOwner, request: LiveEndRequest): Promise<{ ok: true }> {
+ if ("requestId" in request) {
+ const key = `${ownerKey(owner)}:${request.requestId}`;
+ const slot = this.current;
+ if (slot?.requestId === request.requestId && ownerKey(slot.owner) === ownerKey(owner)) await this.endSlot(slot, request.reason);
+ else {
+ this.cancellationTombstones.set(key, this.now() + 2 * 60_000);
+ this.pruneTombstones();
+ }
+ return { ok: true };
+ }
+ const slot = this.requireCurrent(owner, request.callId, true);
+ await this.endSlot(slot, request.reason);
+ return { ok: true };
+ }
+
+ heartbeat(owner: LiveOwner, callId: string): { ok: true } {
+ const slot = this.requireCurrent(owner, callId);
+ slot.heartbeatAt = this.now();
+ this.armHeartbeat(slot);
+ return { ok: true };
+ }
+
+ beginSettingsWrite(nextSettings: unknown): () => void {
+ if (this.settingsWritePending) throw liveError("LIVE_SETTINGS_IN_USE");
+ const next = liveVoiceFromSettings(nextSettings);
+ if (next.invalid) throw Object.assign(new Error("liveVoice settings are invalid"), { errorCode: ErrorCodes.INVALID_PARAMS });
+ const slot = this.current;
+ if (slot && next.value.enabled) {
+ const lockedBindingId = slot.binding?.id ?? slot.requestedBindingId;
+ const nextBinding = next.value.bindings.find((binding) => binding.id === lockedBindingId);
+ const lockedBinding = slot.binding ?? this.settingsSnapshot?.value.bindings.find((binding) => binding.id === lockedBindingId);
+ if (!nextBinding || !lockedBinding || fingerprint(nextBinding) !== fingerprint(lockedBinding)) throw liveError("LIVE_SETTINGS_IN_USE");
+ if (!slot.binding && next.value.selectedBindingId && next.value.selectedBindingId !== lockedBindingId) throw liveError("LIVE_SETTINGS_IN_USE");
+ }
+ this.settingsWritePending = true;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ this.settingsWritePending = false;
+ };
+ }
+
+ async settingsWritten(settings: AppSettings): Promise<void> {
+ const previous = this.settingsSnapshot;
+ const raw = liveVoiceFromSettings(settings);
+ const nextFingerprint = fingerprint(raw.value);
+ const revision = previous ? previous.revision + (previous.fingerprint === nextFingerprint ? 0 : 1) : 1;
+ this.settingsSnapshot = { value: raw.value, invalid: raw.invalid, fingerprint: nextFingerprint, revision };
+ if (!raw.value.enabled && this.current) await this.endSlot(this.current, "disabled");
+ }
+
+ async invalidateProvider(providerId: string): Promise<void> {
+ const slot = this.current;
+ if (slot?.binding?.providerId === providerId) await this.endSlot(slot, "provider-invalidated");
+ }
+
+ async endForLifecycle(reason: LiveEndReason, owner?: LiveOwner, ownerGone = false): Promise<void> {
+ if (ownerGone && owner) this.ownerDestroyed(owner);
+ const slot = this.current;
+ if (slot && (!owner || ownerKey(slot.owner) === ownerKey(owner))) await this.endSlot(slot, reason, ownerGone);
+ }
+
+ ownerDestroyed(owner: LiveOwner): void {
+ const slot = this.current;
+ if (slot && ownerKey(slot.owner) === ownerKey(owner)) {
+ slot.microphoneActive = false;
+ slot.mediaRelease = "confirmed";
+ slot.resolveMediaReleased?.();
+ slot.resolveMediaReleased = null;
+ }
+ if (this.quarantine && ownerKey(this.quarantine.owner) === ownerKey(owner)) {
+ this.quarantine.releaseMicrophone?.();
+ this.quarantine = null;
+ }
+ }
+
+ async endForWebContents(webContentsId: number, reason: LiveEndReason, ownerGone = false): Promise<void> {
+ const slot = this.current;
+ if (!slot || slot.owner.webContentsId !== webContentsId) return;
+ if (ownerGone) this.ownerDestroyed(slot.owner);
+ await this.endSlot(slot, reason, ownerGone);
+ }
+
+ private async runPrepare(slot: Slot, request: LivePrepareRequest): Promise<LivePreparedCall> {
+ const snapshot = await this.withDeadline(this.readSettings(), PREPARE_DEADLINE_MS, "prepare");
+ this.assertCurrent(slot);
+ if (snapshot.invalid) throw liveError("LIVE_NOT_CONFIGURED");
+ if (!snapshot.value.enabled) throw liveError("LIVE_DISABLED");
+ if (request.expectedSettingsRevision !== snapshot.revision) throw liveError("LIVE_SETTINGS_IN_USE");
+ const binding = snapshot.value.bindings.find((item) => item.id === request.bindingId);
+ if (!binding) throw liveError("LIVE_NOT_CONFIGURED");
+ if (snapshot.value.selectedBindingId && snapshot.value.selectedBindingId !== binding.id) throw liveError("LIVE_NOT_CONFIGURED");
+ const record = await this.withDeadline(this.deps.authResolver.provider(binding.providerId), PREPARE_DEADLINE_MS, "prepare");
+ this.assertCurrent(slot);
+ if (!record?.provider?.enabled) throw liveError("LIVE_PROVIDER_NOT_FOUND");
+ if (!this.providerMatches(binding, record.provider)) throw liveError("LIVE_AUTH_KIND_UNSUPPORTED");
+ if (!record.provider.hasSecret) throw liveError("LIVE_AUTH_REQUIRED");
+ slot.binding = Object.freeze({ ...binding });
+ slot.settingsRevision = snapshot.revision;
+ transition(slot, "acquiring-mic");
+ if (binding.adapterId === "gemini-live" || binding.adapterId === "openai-realtime") {
+ slot.bridge = this.deps.createPcmBridge({
+ callId: slot.callId,
+ owner: slot.owner,
+ inputSampleRate: binding.adapterId === "gemini-live" ? 16000 : 24000,
+ outputSampleRate: 24000,
+ onInput: (bytes, epoch) => this.onInput(slot, bytes, epoch),
+ onPlaybackPosition: () => undefined,
+ onReleased: () => this.confirmMediaReleased(slot),
+ onFailure: (code) => { void this.failAndCleanup(slot, liveError(code), "media"); },
+ });
+ }
+ slot.releaseBackgroundLease = this.deps.acquireBackgroundThrottlingLease?.(slot.callId) ?? null;
+ slot.reservationTimer = setTimeout(() => {
+ if (this.current === slot && slot.phase !== "connected") void this.failAndCleanup(slot, liveError("LIVE_TIMEOUT"), "permission");
+ }, RESERVATION_TIMEOUT_MS);
+ this.armHeartbeat(slot);
+ this.publish(slot);
+ const prepared: Omit<LivePreparedCall, "mediaKind" | "portNonce"> = {
+ callId: slot.callId,
+ requestId: slot.requestId,
+ bindingId: binding.id,
+ adapterId: binding.adapterId,
+ inputSampleRate: binding.adapterId === "gemini-live" ? 16000 : 24000,
+ outputSampleRate: 24000,
+ initialMuted: slot.desiredMuted,
+ revision: slot.revision,
+ };
+ if (binding.adapterId === "codex-live") return { ...prepared, mediaKind: "webrtc" };
+ if (!slot.bridge) throw liveError("LIVE_PROTOCOL_ERROR");
+ return { ...prepared, mediaKind: "pcm", portNonce: slot.bridge.portNonce };
+ }
+
+ private async runConnect(slot: Slot, offerSdp?: string): Promise<{ answerSdp?: string; revision: number }> {
+ this.assertCurrent(slot);
+ if (!slot.binding) throw liveError("LIVE_STALE_CALL");
+ if (slot.binding.adapterId !== "codex-live" && !slot.bridge) throw liveError("LIVE_PROTOCOL_ERROR");
+ if (slot.binding.adapterId === "codex-live" && !offerSdp) throw liveError("LIVE_PROTOCOL_ERROR");
+ if (slot.reservationTimer) clearTimeout(slot.reservationTimer);
+ if (slot.phase === "acquiring-mic") transition(slot, slot.binding.adapterId === "codex-live" ? "negotiating" : "connecting");
+ this.publish(slot);
+ const totalTimer = setTimeout(() => slot.abort.abort(new Error("Live call startup timed out")), TOTAL_CONNECT_TIMEOUT_MS);
+ try {
+ const result = await this.withDeadline(
+ this.deps.authResolver.resolve(slot.binding),
+ AUTH_TIMEOUT_MS,
+ "auth",
+ slot.abort.signal,
+ );
+ this.assertCurrent(slot);
+ await this.assertBindingStillConfigured(slot);
+ this.assertCurrent(slot);
+ const context: LiveAdapterContext = {
+ callId: slot.callId,
+ binding: slot.binding,
+ provider: result.provider,
+ auth: result.auth as LiveResolvedAuth,
+ signal: slot.abort.signal,
+ onEvent: (event) => this.onAdapterEvent(slot, event),
+ };
+ slot.adapter = this.deps.createAdapter(context);
+ if (slot.bridge) {
+ await this.withDeadline(slot.bridge.ready, CONNECT_TIMEOUT_MS, "media", slot.abort.signal);
+ this.assertCurrent(slot);
+ }
+ const connected = await this.withDeadline(
+ slot.adapter.connect(slot.binding.adapterId === "codex-live" ? { offerSdp } : undefined),
+ CONNECT_TIMEOUT_MS,
+ "handshake",
+ slot.abort.signal,
+ );
+ this.assertCurrent(slot);
+ if (slot.phase === "negotiating") transition(slot, "connecting");
+ if (slot.adapter.mediaKind === "pcm" && !slot.desiredMuted) {
+ const nextEpoch = slot.captureEpoch + 1;
+ await slot.bridge?.setMuted(false, nextEpoch);
+ slot.captureEpoch = nextEpoch;
+ slot.muted = false;
+ await slot.adapter.setInputMuted?.(false);
+ }
+ this.publish(slot);
+ return { ...(connected.answerSdp ? { answerSdp: connected.answerSdp } : {}), revision: slot.revision };
+ } catch (error) {
+ if (slot.abort.signal.aborted && !(error && typeof error === "object" && "errorCode" in error)) {
+ throw liveError("LIVE_TIMEOUT");
+ }
+ throw error;
+ } finally {
+ clearTimeout(totalTimer);
+ }
+ }
+
+ private async assertBindingStillConfigured(slot: Slot): Promise<void> {
+ if (!slot.binding) throw liveError("LIVE_STALE_CALL");
+ const snapshot = await this.readSettings();
+ this.assertCurrent(slot);
+ const binding = snapshot.value.bindings.find((candidate) => candidate.id === slot.binding?.id);
+ if (snapshot.invalid || !snapshot.value.enabled || !binding || fingerprint(binding) !== fingerprint(slot.binding)) throw liveError("LIVE_SETTINGS_IN_USE");
+ if (snapshot.revision !== slot.settingsRevision) {
+ const current = snapshot.value.bindings.find((candidate) => candidate.id === slot.binding?.id);
+ if (!current || fingerprint(current) !== fingerprint(slot.binding)) throw liveError("LIVE_SETTINGS_IN_USE");
+ }
+ }
+
+ private onInput(slot: Slot, bytes: Uint8Array, epoch: number): void {
+ if (this.current !== slot || slot.phase !== "connected" || slot.muted || slot.desiredMuted || epoch !== slot.captureEpoch || !slot.adapter?.sendInputPcm) return;
+ try { slot.adapter.sendInputPcm(bytes); }
+ catch (error) { void this.failAndCleanup(slot, error, "media"); }
+ }
+
+ private onAdapterEvent(slot: Slot, event: LiveWireEvent): void {
+ if (this.current !== slot || slot.abort.signal.aborted) return;
+ switch (event.kind) {
+ case "ready":
+ if (slot.phase === "connecting") this.publish(slot);
+ return;
+ case "audio":
+ if (!slot.bridge || slot.phase === "closing" || slot.phase === "failed") return;
+ try {
+ slot.bridge.sendOutput({ bytes: event.bytes, playbackEpoch: slot.playbackEpoch, ...(event.responseId ? { responseId: event.responseId } : {}), ...(event.itemId ? { itemId: event.itemId } : {}), ...(event.contentIndex !== undefined ? { contentIndex: event.contentIndex } : {}) });
+ } catch (error) { void this.failAndCleanup(slot, error, "playback"); }
+ return;
+ case "transcript":
+ this.pushTranscript(slot, event);
+ return;
+ case "activity":
+ if (event.userSpeaking !== undefined) slot.userSpeaking = event.userSpeaking;
+ if (event.assistantSpeaking !== undefined) slot.assistantSpeaking = event.assistantSpeaking;
+ this.publish(slot);
+ return;
+ case "interrupted":
+ slot.playbackEpoch += 1;
+ if (slot.bridge) {
+ void slot.bridge.interrupt().then((cursors) => {
+ if (this.current !== slot) return;
+ return slot.adapter?.interrupt?.(cursors);
+ }).catch((error: unknown) => this.failAndCleanup(slot, error, "playback"));
+ }
+ slot.assistantSpeaking = false;
+ this.publish(slot);
+ return;
+ case "delegation":
+ if (slot.binding?.adapterId !== "codex-live") {
+ void slot.adapter?.rejectDelegation?.({ callId: slot.callId, delegationId: event.delegationId });
+ slot.notice = { code: "LIVE_EXECUTION_NOT_CONNECTED", retriable: false };
+ this.publish(slot);
+ }
+ return;
+ case "tool-call-cancelled":
+ // Live providers have no local tool execution path in this release.
+ // The adapter validates cancellations so a later tool-capable profile
+ // cannot accidentally leave work running without adding a new parser.
+ return;
+ case "error":
+ if (event.code === "LIVE_EXECUTION_NOT_CONNECTED") {
+ slot.notice = { code: event.code, retriable: false };
+ this.publish(slot);
+ } else void this.failAndCleanup(slot, liveError(event.code), "protocol");
+ return;
+ case "turn-complete":
+ slot.assistantSpeaking = false;
+ this.publish(slot);
+ return;
+ case "closed":
+ if (slot.phase !== "closing") void this.failAndCleanup(slot, liveError("LIVE_NETWORK_ERROR"), "connection");
+ return;
+ }
+ }
+
+ private pushTranscript(slot: Slot, event: Extract<LiveWireEvent, { kind: "transcript" }>): void {
+ const text = event.text.slice(0, 16_384);
+ if (!text) return;
+ const key = `${event.role}\u0000${event.id.slice(0, 256)}`;
+ const bytes = Buffer.byteLength(text, "utf8");
+ const priorBytes = slot.transcriptLengths.get(key) ?? 0;
+ while (
+ (!slot.transcriptLengths.has(key) && slot.transcriptLengths.size >= MAX_TRANSCRIPT_SEGMENTS) ||
+ [...slot.transcriptLengths.values()].reduce((sum, size) => sum + size, 0) - priorBytes + bytes > MAX_TRANSCRIPT_BYTES
+ ) {
+ const oldest = slot.transcriptLengths.keys().next().value;
+ if (oldest === undefined || oldest === key) break;
+ slot.transcriptLengths.delete(oldest);
+ }
+ slot.transcriptLengths.set(key, bytes);
+ this.deps.sendTranscript(slot.owner, {
+ callId: slot.callId,
+ segment: { id: event.id.slice(0, 256), role: event.role, text, final: event.final, timestamp: this.now() },
+ });
+ }
+
+ private async endSlot(slot: Slot, reason: LiveEndReason, ownerGone = false): Promise<void> {
+ if (slot.phase === "ended" || slot.phase === "failed") return;
+ if (slot.phase !== "closing") transition(slot, "closing");
+ slot.muted = true;
+ slot.desiredMuted = true;
+ this.publish(slot);
+ slot.abort.abort(new Error(reason));
+ this.clearTimers(slot);
+ if (!ownerGone && this.deps.ownerAlive(slot.owner)) {
+ slot.mediaRelease = "pending";
+ this.publish(slot);
+ this.deps.sendControl(slot.owner, { callId: slot.callId, kind: "release-media" });
+ await this.withDeadline(slot.mediaReleased, 1_000, "cleanup").catch(() => undefined);
+ } else {
+ this.confirmMediaReleased(slot);
+ }
+ const adapterClose = slot.adapter?.close(reason) ?? Promise.resolve();
+ slot.bridge?.close();
+ await this.withDeadline(adapterClose, 1_000, "cleanup").catch(() => undefined);
+ for (const pending of slot.pendingControls.values()) clearTimeout(pending.timer);
+ slot.pendingControls.clear();
+ slot.releaseBackgroundLease?.();
+ slot.releaseBackgroundLease = null;
+ if (slot.mediaRelease === "confirmed") {
+ slot.releaseMicrophone?.();
+ slot.releaseMicrophone = null;
+ } else {
+ this.quarantine = { owner: slot.owner, releaseMicrophone: slot.releaseMicrophone };
+ slot.releaseMicrophone = null;
+ slot.mediaRelease = "unconfirmed";
+ slot.error = { code: "LIVE_MEDIA_RELEASE_UNCONFIRMED", stage: "cleanup", retriable: false };
+ }
+ transition(slot, slot.error ? "failed" : "ended");
+ this.publish(slot);
+ this.terminal = this.toView(slot);
+ if (this.current === slot) this.current = null;
+ }
+
+ private async failAndCleanup(slot: Slot, error: unknown, stage: string): Promise<void> {
+ if (this.current !== slot) return;
+ if (!slot.error) slot.error = { ...errorCode(error), stage };
+ await this.endSlot(slot, slot.error.code === "LIVE_TIMEOUT" ? "timeout" : slot.error.code === "LIVE_AUDIO_BACKPRESSURE" ? "audio-backpressure" : "network-error");
+ }
+
+ private confirmMediaReleased(slot: Slot): void {
+ slot.microphoneActive = false;
+ slot.mediaRelease = "confirmed";
+ slot.resolveMediaReleased?.();
+ slot.resolveMediaReleased = null;
+ }
+
+ private startCallTimers(slot: Slot): void {
+ if (!slot.maxDurationTimer) {
+ slot.maxDurationTimer = setTimeout(() => {
+ if (this.current === slot) void this.failAndCleanup(slot, liveError("LIVE_TIMEOUT"), "connection");
+ }, MAX_CALL_MS);
+ }
+ if (slot.reservationTimer) clearTimeout(slot.reservationTimer);
+ slot.reservationTimer = undefined;
+ }
+
+ private armHeartbeat(slot: Slot): void {
+ if (slot.heartbeatTimer) clearTimeout(slot.heartbeatTimer);
+ slot.heartbeatTimer = setTimeout(() => {
+ if (this.current !== slot || slot.phase === "closing") return;
+ if (this.now() - slot.heartbeatAt >= OWNER_LEASE_MS) {
+ void this.failAndCleanup(slot, liveError("LIVE_TIMEOUT"), "owner");
+ return;
+ }
+ this.armHeartbeat(slot);
+ }, OWNER_HEARTBEAT_MS);
+ }
+
+ private async readSettings(): Promise<SettingsSnapshot> {
+ const raw = await this.deps.loadSettings();
+ const parsed = liveVoiceFromSettings(raw);
+ const nextFingerprint = fingerprint(parsed.value);
+ if (!this.settingsSnapshot) {
+ this.settingsSnapshot = { value: parsed.value, invalid: parsed.invalid, fingerprint: nextFingerprint, revision: 1 };
+ } else if (this.settingsSnapshot.fingerprint !== nextFingerprint || this.settingsSnapshot.invalid !== parsed.invalid) {
+ this.settingsSnapshot = { value: parsed.value, invalid: parsed.invalid, fingerprint: nextFingerprint, revision: this.settingsSnapshot.revision + 1 };
+ }
+ return this.settingsSnapshot;
+ }
+
+ private providerMatches(binding: LiveBinding, provider: { enabled: boolean; authKind: string; vendorKey: string; apiStyle?: string; baseUrl?: string }): boolean {
+ if (!provider.enabled) return false;
+ if (binding.adapterId === "codex-live") return provider.authKind === OAUTH_AUTH_KIND && provider.vendorKey === "openai-codex";
+ if (provider.authKind === OAUTH_AUTH_KIND) return false;
+ if (binding.adapterId === "gemini-live") return provider.vendorKey === "google" && provider.apiStyle === "google_generative_ai";
+ return Boolean(provider.baseUrl);
+ }
+
+ private async withDeadline<T>(promise: Promise<T>, timeoutMs: number, stage: string, signal?: AbortSignal): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let abortListener: (() => void) | undefined;
+ const timeout = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(Object.assign(new Error(`Live ${stage} stage timed out`), { errorCode: "LIVE_TIMEOUT" })), timeoutMs);
+ });
+ const aborted = new Promise<never>((_, reject) => {
+ if (!signal) return;
+ abortListener = () => reject(Object.assign(new Error("Live call was cancelled"), { errorCode: "LIVE_STALE_CALL" }));
+ if (signal.aborted) abortListener();
+ else signal.addEventListener("abort", abortListener, { once: true });
+ });
+ try { return await Promise.race([promise, timeout, aborted]); }
+ finally {
+ if (timer) clearTimeout(timer);
+ if (abortListener && signal) signal.removeEventListener("abort", abortListener);
+ }
+ }
+
+ private makeSlot(owner: LiveOwner, request: LivePrepareRequest): Slot {
+ let resolveMediaReleased: (() => void) | null = null;
+ const mediaReleased = new Promise<void>((resolve) => { resolveMediaReleased = resolve; });
+ return {
+ callId: randomUUID(),
+ requestId: request.requestId,
+ requestedBindingId: request.bindingId,
+ owner: { ...owner },
+ binding: null,
+ settingsRevision: request.expectedSettingsRevision,
+ phase: "preparing",
+ revision: 0,
+ abort: new AbortController(),
+ desiredMuted: request.initialMuted,
+ muted: true,
+ captureEpoch: 0,
+ playbackEpoch: 0,
+ microphoneActive: false,
+ mediaRelease: "confirmed",
+ mediaReleased,
+ resolveMediaReleased,
+ userSpeaking: false,
+ assistantSpeaking: false,
+ adapter: null,
+ bridge: null,
+ releaseMicrophone: null,
+ releaseBackgroundLease: null,
+ heartbeatAt: this.now(),
+ delegationInstructions: new Map(),
+ pendingControls: new Map(),
+ transcriptLengths: new Map(),
+ };
+ }
+
+ private requireCurrent(owner: LiveOwner, callId: string, allowClosing = false): Slot {
+ const slot = this.current;
+ if (!slot || slot.callId !== callId) throw liveError("LIVE_STALE_CALL");
+ if (ownerKey(slot.owner) !== ownerKey(owner)) throw liveError("LIVE_INVALID_OWNER");
+ if (!allowClosing && (slot.phase === "closing" || slot.phase === "ended" || slot.phase === "failed")) throw liveError("LIVE_STALE_CALL");
+ return slot;
+ }
+
+ private assertCurrent(slot: Slot): void {
+ if (this.current !== slot || slot.abort.signal.aborted) throw liveError("LIVE_STALE_CALL");
+ }
+
+ private toView(slot: Slot): LiveCallView {
+ return {
+ callId: slot.callId,
+ revision: slot.revision,
+ bindingId: slot.binding?.id ?? "",
+ adapterId: slot.binding?.adapterId ?? "codex-live",
+ phase: slot.phase,
+ muted: slot.muted,
+ microphoneActive: slot.microphoneActive,
+ userSpeaking: slot.userSpeaking,
+ assistantSpeaking: slot.assistantSpeaking,
+ ...(slot.connectedAt ? { connectedAt: slot.connectedAt } : {}),
+ ...(slot.playbackBlocked !== undefined ? { playbackBlocked: slot.playbackBlocked } : {}),
+ mediaRelease: slot.mediaRelease,
+ ...(slot.error ? { error: slot.error } : {}),
+ ...(slot.notice ? { notice: slot.notice } : {}),
+ };
+ }
+
+ private publish(slot: Slot): void {
+ slot.revision += 1;
+ if (this.current === slot) {
+ try { this.deps.sendView(slot.owner, this.toView(slot)); } catch { /* The lifecycle watcher closes a disappeared owner. */ }
+ }
+ }
+
+ private clearTimers(slot: Slot): void {
+ for (const timer of [slot.reservationTimer, slot.heartbeatTimer, slot.maxDurationTimer]) if (timer) clearTimeout(timer);
+ }
+
+ private trimRequests(): void {
+ while (this.requests.size > MAX_CALLS_PER_OWNER_REQUEST_CACHE) {
+ const first = this.requests.keys().next().value;
+ if (first === undefined) return;
+ if (this.current && first.endsWith(`:${this.current.requestId}`)) return;
+ this.requests.delete(first);
+ }
+ }
+
+ private pruneTombstones(): void {
+ const now = this.now();
+ for (const [key, expiresAt] of this.cancellationTombstones) if (expiresAt <= now) this.cancellationTombstones.delete(key);
+ while (this.cancellationTombstones.size > 128) {
+ const first = this.cancellationTombstones.keys().next().value;
+ if (first === undefined) return;
+ this.cancellationTombstones.delete(first);
+ }
+ }
+}
+
+function validatePrepareRequest(request: LivePrepareRequest): void {
+ if (!request || typeof request !== "object" || !/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(request.requestId) || typeof request.bindingId !== "string" || request.bindingId.length > 256 || !Number.isSafeInteger(request.expectedSettingsRevision) || typeof request.initialMuted !== "boolean") {
+ throw liveError("LIVE_PROTOCOL_ERROR");
+ }
+}
+
+function liveError(code: string): Error {
+ return Object.assign(new Error(code), { errorCode: code });
+}
diff --git a/apps/desktop/electron/main/live-voice/codex-adapter.ts b/apps/desktop/electron/main/live-voice/codex-adapter.ts
new file mode 100644
index 000000000..201f051d5
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/codex-adapter.ts
@@ -0,0 +1,109 @@
+import { randomUUID } from "node:crypto";
+import { ErrorCodes, type LiveBinding } from "@pi-desktop/shared";
+import type { LiveAdapter, LiveAdapterContext } from "./types";
+import { responseCodeError } from "./websocket-errors";
+import { extractCodexSdpAnswer, normalizeCodexSdp, readResponseTextBounded } from "./codex-sdp";
+
+const CODEX_LIVE_BASE = "https://chatgpt.com/backend-api/codex";
+const CODEX_MODEL = "gpt-live-1-codex";
+const MAX_SDP_BYTES = 256 * 1024;
+const MAX_SDP_RESPONSE_BYTES = 256 * 1024;
+const STARTUP_INSTRUCTIONS = "You are a voice assistant. Do not claim to execute actions. You have no access to project files, tools, or the coding agent. If asked to perform work, explain that execution is not connected.";
+
+export function buildCodexCallBody(input: { sdp: string; voice: string }): Record<string, unknown> {
+ return {
+ sdp: input.sdp,
+ session: {
+ model: CODEX_MODEL,
+ instructions: STARTUP_INSTRUCTIONS,
+ audio: { output: { voice: input.voice } },
+ delegation: { type: "client", ack_filler: false },
+ },
+ };
+}
+
+export function createCodexAdapter(context: LiveAdapterContext, deps: {
+ fetchImpl?: typeof fetch;
+ assertEndpoint: (url: string) => Promise<void>;
+}): LiveAdapter {
+ let closed = false;
+ let requestController: AbortController | null = null;
+ const binding = context.binding as Extract<LiveBinding, { adapterId: "codex-live" }>;
+ const auth = context.auth;
+
+ return {
+ adapterId: "codex-live",
+ mediaKind: "webrtc",
+ async connect(input) {
+ if (!input?.offerSdp) {
+ throw Object.assign(new Error("Live SDP offer is invalid or too large"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ }
+ const offerSdp = normalizeCodexSdp(input.offerSdp, MAX_SDP_BYTES);
+ if (auth.kind !== "codex-oauth") {
+ throw Object.assign(new Error("Codex Live requires a signed-in Codex account"), { errorCode: "LIVE_AUTH_KIND_UNSUPPORTED" });
+ }
+ if (closed || context.signal.aborted) throw Object.assign(new Error("Live call was cancelled"), { errorCode: "LIVE_STALE_CALL" });
+ const url = `${CODEX_LIVE_BASE}/realtime/calls?intent=quicksilver&architecture=avas`;
+ await deps.assertEndpoint(url);
+ requestController = new AbortController();
+ const onAbort = () => requestController?.abort(context.signal.reason);
+ context.signal.addEventListener("abort", onAbort, { once: true });
+ const timeout = setTimeout(() => requestController?.abort(new Error("timeout")), 15_000);
+ try {
+ const headers = {
+ Authorization: `Bearer ${auth.accessToken}`,
+ "chatgpt-account-id": auth.accountId,
+ originator: "pi",
+ "x-session-id": randomUUID(),
+ "user-agent": "pi-codex-conversion",
+ "openai-alpha": "quicksilver=v2",
+ "content-type": "application/json",
+ };
+ const response = await (deps.fetchImpl ?? fetch)(url, {
+ method: "POST",
+ headers,
+ body: JSON.stringify(buildCodexCallBody({ sdp: offerSdp, voice: binding.voice })),
+ signal: requestController.signal,
+ redirect: "manual",
+ });
+ if (response.status !== 201) {
+ await response.body?.cancel().catch(() => undefined);
+ const mapped = responseCodeError(response.status);
+ throw Object.assign(new Error("Codex Live call creation was rejected"), {
+ errorCode: mapped.code,
+ retriable: mapped.retriable,
+ });
+ }
+ const contentLength = Number(response.headers.get("content-length"));
+ if (Number.isFinite(contentLength) && contentLength > MAX_SDP_RESPONSE_BYTES) {
+ await response.body?.cancel().catch(() => undefined);
+ throw Object.assign(new Error("Live provider SDP answer is too large"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ }
+ const answerSdp = extractCodexSdpAnswer(await readResponseTextBounded(response, MAX_SDP_RESPONSE_BYTES));
+ if (closed || context.signal.aborted) throw Object.assign(new Error("Live call was cancelled"), { errorCode: "LIVE_STALE_CALL" });
+ return { answerSdp };
+ } catch (error) {
+ if (error && typeof error === "object" && "errorCode" in error) throw error;
+ if (requestController.signal.aborted) {
+ throw Object.assign(new Error("Codex Live call creation timed out or was cancelled"), {
+ errorCode: context.signal.aborted ? "LIVE_STALE_CALL" : "LIVE_TIMEOUT",
+ });
+ }
+ throw Object.assign(new Error("Codex Live connection failed"), {
+ errorCode: ErrorCodes.LIVE_NETWORK_ERROR,
+ cause: error,
+ });
+ } finally {
+ clearTimeout(timeout);
+ context.signal.removeEventListener("abort", onAbort);
+ requestController = null;
+ }
+ },
+ async close() {
+ if (closed) return;
+ closed = true;
+ requestController?.abort();
+ requestController = null;
+ },
+ };
+}
diff --git a/apps/desktop/electron/main/live-voice/codex-sdp.ts b/apps/desktop/electron/main/live-voice/codex-sdp.ts
new file mode 100644
index 000000000..2c268912e
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/codex-sdp.ts
@@ -0,0 +1,65 @@
+const MAX_SDP_BYTES = 256 * 1024;
+
+function protocolError(message: string): Error & { errorCode: string } {
+ return Object.assign(new Error(message), { errorCode: "LIVE_PROTOCOL_ERROR" });
+}
+
+export function normalizeCodexSdp(value: string, maxBytes = MAX_SDP_BYTES): string {
+ if (Buffer.byteLength(value, "utf8") > maxBytes || value.includes("\0")) {
+ throw protocolError("Live provider SDP is invalid or too large");
+ }
+ const lines = value.trim().replace(/\r\n?/g, "\n").split("\n");
+ while (lines.at(-1) === "") lines.pop();
+ if (!lines.length || lines[0] !== "v=0") throw protocolError("Live provider returned an invalid SDP version");
+ return `${lines.join("\r\n")}\r\n`;
+}
+
+export function extractCodexSdpAnswer(raw: string): string {
+ if (Buffer.byteLength(raw, "utf8") > MAX_SDP_BYTES || raw.includes("\0")) {
+ throw protocolError("Live provider SDP answer is invalid or too large");
+ }
+ const trimmed = raw.trim();
+ let candidate = trimmed;
+ if (!trimmed.startsWith("v=0")) {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(trimmed) as unknown;
+ } catch {
+ throw protocolError("Live provider returned an invalid SDP answer");
+ }
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
+ throw protocolError("Live provider returned an invalid SDP answer");
+ }
+ const record = parsed as Record<string, unknown>;
+ if (Object.keys(record).length !== 1 || typeof record.sdp !== "string") {
+ throw protocolError("Live provider returned an invalid SDP answer");
+ }
+ candidate = record.sdp;
+ }
+ return normalizeCodexSdp(candidate);
+}
+
+export async function readResponseTextBounded(response: Response, maxBytes = MAX_SDP_BYTES): Promise<string> {
+ const reader = response.body?.getReader();
+ if (!reader) return "";
+ const decoder = new TextDecoder();
+ let size = 0;
+ let result = "";
+ try {
+ while (true) {
+ const chunk = await reader.read();
+ if (chunk.done) {
+ result += decoder.decode();
+ return result;
+ }
+ size += chunk.value.byteLength;
+ if (size > maxBytes) {
+ await reader.cancel().catch(() => undefined);
+ throw protocolError("Live provider SDP answer is too large");
+ }
+ result += decoder.decode(chunk.value, { stream: true });
+ }
+ } finally {
+ reader.releaseLock();
+ }
+}
diff --git a/apps/desktop/electron/main/live-voice/gemini-adapter.ts b/apps/desktop/electron/main/live-voice/gemini-adapter.ts
new file mode 100644
index 000000000..1c0ac2149
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/gemini-adapter.ts
@@ -0,0 +1,108 @@
+import type { LiveBinding } from "@pi-desktop/shared";
+import { geminiAudioEndMessage, geminiAudioMessage, geminiSetupMessage, MAX_LIVE_AUDIO_BYTES, MAX_LIVE_JSON_BYTES, parseGeminiMessage } from "@pi-desktop/voice-runtime/live";
+import type { LiveAdapter, LiveAdapterContext } from "./types";
+import { openLiveWebSocket } from "./websocket-transport";
+import { sendJsonBounded, waitForReady, waitForSocketReady, websocketJson } from "./websocket-wire";
+import { WebSocket } from "ws";
+
+const GEMINI_LIVE_ENDPOINT = "wss://generativelanguage.googleapis.com/ws/google.ai.generativelanguage.v1beta.GenerativeService.BidiGenerateContent";
+const MAX_FRAME_BYTES = 16000 * 2 / 10;
+
+export function createGeminiAdapter(context: LiveAdapterContext): LiveAdapter {
+ const binding = context.binding as Extract<LiveBinding, { adapterId: "gemini-live" }>;
+ if (context.auth.kind !== "api-key") {
+ throw Object.assign(new Error("Gemini Live requires a Provider API key"), { errorCode: "LIVE_AUTH_KIND_UNSUPPORTED" });
+ }
+ const apiKey = context.auth.apiKey;
+ let socket: Awaited<ReturnType<typeof openLiveWebSocket>> | null = null;
+ let closed = false;
+ let muted = context.signal.aborted;
+ let readyResolve: (() => void) | null = null;
+ let readyReject: ((error: Error) => void) | null = null;
+ const ready = new Promise<void>((resolve, reject) => { readyResolve = resolve; readyReject = reject; });
+
+ function onSocketMessage(data: unknown): void {
+ try {
+ const value = websocketJson(data, MAX_LIVE_JSON_BYTES);
+ const root = value as Record<string, unknown>;
+ const server = root.serverContent as Record<string, unknown> | undefined;
+ const toolCall = root.toolCall as Record<string, unknown> | undefined;
+ if (toolCall) {
+ const calls = Array.isArray(toolCall.functionCalls) ? toolCall.functionCalls : [];
+ if (calls.length > 16) throw new Error("tool call limit exceeded");
+ for (const call of calls) {
+ const item = call as Record<string, unknown>;
+ if (typeof item.id !== "string" || typeof item.name !== "string") throw new Error("tool call shape invalid");
+ sendJsonBounded(socket!, {
+ toolResponse: {
+ functionResponses: [{ id: item.id, name: item.name, response: { output: "Execution is not connected. No work was performed." } }],
+ },
+ });
+ context.onEvent({ kind: "error", code: "LIVE_EXECUTION_NOT_CONNECTED" });
+ }
+ }
+ if (server?.modelTurn && typeof server.modelTurn === "object") {
+ const parts = (server.modelTurn as { parts?: unknown[] }).parts;
+ if (Array.isArray(parts)) {
+ for (const part of parts) {
+ const inline = part && typeof part === "object" ? (part as { inlineData?: unknown }).inlineData : null;
+ if (inline && typeof inline === "object") {
+ const mimeType = (inline as { mimeType?: unknown }).mimeType;
+ if (typeof mimeType === "string" && !/audio\/pcm;rate=24000/i.test(mimeType)) {
+ throw new Error("unsupported Gemini audio sample rate");
+ }
+ }
+ }
+ }
+ }
+ for (const event of parseGeminiMessage(value)) {
+ if (event.kind === "ready") readyResolve?.();
+ context.onEvent(event);
+ }
+ } catch {
+ context.onEvent({ kind: "error", code: "LIVE_PROTOCOL_ERROR" });
+ readyReject?.(Object.assign(new Error("Gemini Live protocol response is invalid"), { errorCode: "LIVE_PROTOCOL_ERROR" }));
+ }
+ }
+
+ return {
+ adapterId: "gemini-live",
+ mediaKind: "pcm",
+ async connect() {
+ if (closed || context.signal.aborted) throw Object.assign(new Error("Live call was cancelled"), { errorCode: "LIVE_STALE_CALL" });
+ const url = new URL(GEMINI_LIVE_ENDPOINT);
+ url.searchParams.set("key", apiKey);
+ const liveSocket = await openLiveWebSocket({ url: url.toString(), signal: context.signal, endpointOrigin: "third-party" });
+ socket = liveSocket;
+ liveSocket.on("message", onSocketMessage);
+ liveSocket.once("close", (code) => {
+ if (!closed) context.onEvent({ kind: "error", code: code === 1000 ? "LIVE_NETWORK_ERROR" : "LIVE_NETWORK_ERROR" });
+ });
+ liveSocket.once("error", () => {
+ if (!closed) context.onEvent({ kind: "error", code: "LIVE_NETWORK_ERROR" });
+ });
+ await waitForSocketReady(liveSocket, context.signal);
+ sendJsonBounded(liveSocket, geminiSetupMessage({ modelId: binding.modelId, voice: binding.voice }));
+ await waitForReady(ready, context.signal, 12_000, "Gemini Live setup timed out");
+ return {};
+ },
+ sendInputPcm(bytes) {
+ if (closed || muted || !socket || socket.readyState !== WebSocket.OPEN) return;
+ if (bytes.byteLength < 2 || bytes.byteLength > MAX_FRAME_BYTES || bytes.byteLength % 2 !== 0 || bytes.byteLength > MAX_LIVE_AUDIO_BYTES) {
+ throw Object.assign(new Error("Gemini Live audio frame is invalid"), { errorCode: "LIVE_AUDIO_BACKPRESSURE" });
+ }
+ sendJsonBounded(socket, geminiAudioMessage(bytes));
+ },
+ async setInputMuted(nextMuted) {
+ muted = nextMuted;
+ if (nextMuted && socket?.readyState === WebSocket.OPEN) sendJsonBounded(socket, geminiAudioEndMessage());
+ },
+ async close() {
+ if (closed) return;
+ closed = true;
+ readyReject?.(new Error("Gemini Live call closed"));
+ if (socket && socket.readyState !== WebSocket.CLOSED) socket.close(1000, "call ended");
+ socket = null;
+ },
+ };
+}
diff --git a/apps/desktop/electron/main/live-voice/microphone-lease.ts b/apps/desktop/electron/main/live-voice/microphone-lease.ts
new file mode 100644
index 000000000..d861ca993
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/microphone-lease.ts
@@ -0,0 +1,26 @@
+export type MicrophoneOwner = "dictation" | "live";
+
+export class MicrophoneLeaseRegistry {
+ private lease: { owner: MicrophoneOwner; token: string } | null = null;
+
+ constructor(private readonly isDictationActive: () => boolean) {}
+
+ acquire(owner: MicrophoneOwner, token: string): () => void {
+ if (this.lease?.owner === "dictation" && !this.isDictationActive()) this.lease = null;
+ if (this.lease && (this.lease.owner !== owner || this.lease.token !== token)) {
+ throw Object.assign(new Error("The microphone is already in use"), { errorCode: "LIVE_MICROPHONE_BUSY" });
+ }
+ this.lease = { owner, token };
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ if (this.lease?.owner === owner && this.lease.token === token) this.lease = null;
+ };
+ }
+
+ isHeld(): boolean {
+ if (this.lease?.owner === "dictation" && !this.isDictationActive()) this.lease = null;
+ return this.lease !== null;
+ }
+}
diff --git a/apps/desktop/electron/main/live-voice/microphone-permissions.ts b/apps/desktop/electron/main/live-voice/microphone-permissions.ts
new file mode 100644
index 000000000..de55edc37
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/microphone-permissions.ts
@@ -0,0 +1,78 @@
+import type { BrowserWindow, Session, WebContents } from "electron";
+import { liveOwnerFromWebContents, isTrustedRendererUrl } from "./owner";
+import type { LiveOwner } from "./call-service";
+
+type PermissionDecision = {
+ permission: string;
+ ownerValid: boolean;
+ leaseActive: boolean;
+ requestKind: "request" | "check";
+ mediaTypes?: readonly string[];
+ mediaType?: string;
+};
+
+export function allowsLiveMicrophonePermission(input: PermissionDecision): boolean {
+ if (input.permission !== "media" || !input.ownerValid || !input.leaseActive) return false;
+ if (input.requestKind === "request") {
+ return Boolean(input.mediaTypes?.length) && input.mediaTypes?.every((type) => type === "audio") === true;
+ }
+ return input.mediaType === "audio" || input.mediaType === "unknown";
+}
+
+export function installLiveMicrophonePermissionHandlers(input: {
+ targetSession: Session;
+ getMainWindow: () => BrowserWindow | null;
+ hasReservation: (owner: LiveOwner) => boolean;
+}): void {
+ input.targetSession.setPermissionRequestHandler((contents, permission, callback, details) => {
+ const owner = requestOwner(input.getMainWindow(), contents, details.requestingUrl, details.isMainFrame);
+ const allowed = allowsLiveMicrophonePermission({
+ permission,
+ ownerValid: owner !== null,
+ leaseActive: owner !== null && input.hasReservation(owner),
+ requestKind: "request",
+ mediaTypes: "mediaTypes" in details ? details.mediaTypes : undefined,
+ });
+ callback(allowed);
+ });
+
+ input.targetSession.setPermissionCheckHandler((contents, permission, requestingOrigin, details) => {
+ const owner = contents ? checkOwner(input.getMainWindow(), contents, requestingOrigin) : null;
+ return allowsLiveMicrophonePermission({
+ permission,
+ ownerValid: owner !== null,
+ leaseActive: owner !== null && input.hasReservation(owner),
+ requestKind: "check",
+ mediaType: details.mediaType,
+ });
+ });
+}
+
+function requestOwner(
+ window: BrowserWindow | null,
+ contents: WebContents,
+ requestingUrl: string,
+ isMainFrame: boolean,
+): LiveOwner | null {
+ if (!isMainFrame) return null;
+ const owner = liveOwnerFromWebContents(window, contents);
+ return owner && owner.url === requestingUrl ? owner : null;
+}
+
+function checkOwner(window: BrowserWindow | null, contents: WebContents, requestingOrigin: string): LiveOwner | null {
+ const owner = liveOwnerFromWebContents(window, contents);
+ if (!owner || !isTrustedRendererUrl(owner.url)) return null;
+ let protocol: string;
+ let origin: string;
+ try {
+ const parsed = new URL(owner.url);
+ protocol = parsed.protocol;
+ origin = parsed.origin;
+ } catch {
+ return null;
+ }
+ const validOrigin = protocol === "file:"
+ ? requestingOrigin === "file://" || requestingOrigin === "null"
+ : requestingOrigin === origin;
+ return validOrigin ? owner : null;
+}
diff --git a/apps/desktop/electron/main/live-voice/openai-realtime-adapter.ts b/apps/desktop/electron/main/live-voice/openai-realtime-adapter.ts
new file mode 100644
index 000000000..3682a1278
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/openai-realtime-adapter.ts
@@ -0,0 +1,155 @@
+import type { LiveBinding } from "@pi-desktop/shared";
+import { MAX_LIVE_AUDIO_BYTES, MAX_LIVE_JSON_BYTES, parseRealtimeMessage, RealtimeResponseTracker, realtimeAudioMessage, realtimeSessionMatches, realtimeSessionUpdateMessage, realtimeTruncateMessages } from "@pi-desktop/voice-runtime/live";
+import type { LiveAdapter, LiveAdapterContext, LivePlaybackCursor } from "./types";
+import { openLiveWebSocket } from "./websocket-transport";
+import { sendJsonBounded, waitForReady, waitForSocketReady, websocketJson } from "./websocket-wire";
+import { WebSocket } from "ws";
+
+const MAX_FRAME_BYTES = 24000 * 2 / 10;
+
+function realtimeUrl(baseUrl: string, modelId: string): string {
+ let base: URL;
+ try { base = new URL(baseUrl); } catch { throw Object.assign(new Error("Realtime Provider URL is invalid"), { errorCode: "LIVE_PROTOCOL_UNSUPPORTED" }); }
+ if (base.protocol !== "https:" || base.username || base.password || base.search || base.hash) {
+ throw Object.assign(new Error("Realtime Provider must use an HTTPS base URL without credentials or query parameters"), { errorCode: "LIVE_PROTOCOL_UNSUPPORTED" });
+ }
+ let path = base.pathname.replace(/\/+$/, "");
+ if (!path.endsWith("/realtime")) path = `${path}/realtime`;
+ base.pathname = path;
+ base.protocol = "wss:";
+ base.search = "";
+ base.searchParams.set("model", modelId);
+ base.hash = "";
+ return base.toString();
+}
+
+export function createOpenAIRealtimeAdapter(context: LiveAdapterContext): LiveAdapter {
+ const binding = context.binding as Extract<LiveBinding, { adapterId: "openai-realtime" }>;
+ if (context.auth.kind !== "api-key") {
+ throw Object.assign(new Error("Realtime requires an API-key Provider"), { errorCode: "LIVE_AUTH_KIND_UNSUPPORTED" });
+ }
+ const apiKey = context.auth.apiKey;
+ const baseUrl = context.auth.baseUrl;
+ let socket: Awaited<ReturnType<typeof openLiveWebSocket>> | null = null;
+ let closed = false;
+ let muted = true;
+ let createdResolve: (() => void) | null = null;
+ let updatedResolve: (() => void) | null = null;
+ let createdReject: ((error: Error) => void) | null = null;
+ let updatedReject: ((error: Error) => void) | null = null;
+ let sessionUpdateSent = false;
+ let configured = false;
+ const responseTracker = new RealtimeResponseTracker();
+ const rejectedFunctionCalls = new Set<string>();
+ const created = new Promise<void>((resolve, reject) => { createdResolve = resolve; createdReject = reject; });
+ const updated = new Promise<void>((resolve, reject) => { updatedResolve = resolve; updatedReject = reject; });
+
+ function onSocketMessage(data: unknown): void {
+ try {
+ const value = websocketJson(data, MAX_LIVE_JSON_BYTES);
+ const event = value as Record<string, unknown>;
+ let staleCompletion = false;
+ if (event.type === "session.created") {
+ createdResolve?.();
+ if (!sessionUpdateSent) {
+ sessionUpdateSent = true;
+ sendJsonBounded(socket!, realtimeSessionUpdateMessage({ modelId: binding.modelId, voice: binding.voice, profile: binding.wireProfile }));
+ }
+ }
+ if (event.type === "session.updated" && sessionUpdateSent) {
+ if (!realtimeSessionMatches({ session: event.session, modelId: binding.modelId, voice: binding.voice, profile: binding.wireProfile })) {
+ throw Object.assign(new Error("Realtime session confirmation does not match the selected audio profile"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ }
+ configured = true;
+ updatedResolve?.();
+ }
+ if (event.type === "response.created") {
+ const response = event.response && typeof event.response === "object" ? event.response as { id?: unknown } : null;
+ const responseId = typeof response?.id === "string" ? response.id : typeof event.response_id === "string" ? event.response_id : null;
+ if (!responseId) throw Object.assign(new Error("Realtime response omitted its identity"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ responseTracker.add(responseId);
+ }
+ if (event.type === "input_audio_buffer.speech_started") {
+ responseTracker.interrupt();
+ }
+ if (event.type === "response.done" || event.type === "response.cancelled") {
+ const response = event.response && typeof event.response === "object" ? event.response as { id?: unknown } : null;
+ const responseId = typeof event.response_id === "string" ? event.response_id : typeof response?.id === "string" ? response.id : null;
+ if (!responseId) throw Object.assign(new Error("Realtime completion omitted its response identity"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ staleCompletion = responseTracker.finish(responseId);
+ }
+ if (event.type === "error") {
+ const detail = event.error && typeof event.error === "object" ? event.error as { code?: unknown } : null;
+ if (detail?.code === "response_cancel_not_active") return;
+ }
+ if (event.type === "response.output_item.done") {
+ const item = event.item as Record<string, unknown> | undefined;
+ if (item?.type === "function_call" && typeof item.call_id === "string" && typeof item.name === "string" && !rejectedFunctionCalls.has(item.call_id)) {
+ if (rejectedFunctionCalls.size >= 256) throw Object.assign(new Error("Realtime function-call limit exceeded"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ rejectedFunctionCalls.add(item.call_id);
+ sendJsonBounded(socket!, { type: "conversation.item.create", item: { type: "function_call_output", call_id: item.call_id, output: "Execution is not connected. No work was performed." } });
+ sendJsonBounded(socket!, { type: "response.create" });
+ context.onEvent({ kind: "error", code: "LIVE_EXECUTION_NOT_CONNECTED" });
+ }
+ }
+ const normalizedEvents = parseRealtimeMessage(value, binding.wireProfile);
+ for (const normalized of normalizedEvents) {
+ if (normalized.kind === "audio" && normalized.responseId && !responseTracker.shouldAcceptAudio(normalized.responseId)) continue;
+ if (staleCompletion && (normalized.kind === "turn-complete" || (normalized.kind === "activity" && normalized.assistantSpeaking === false))) continue;
+ context.onEvent(normalized);
+ }
+ } catch {
+ context.onEvent({ kind: "error", code: "LIVE_PROTOCOL_ERROR" });
+ const failure = Object.assign(new Error("Realtime protocol response is invalid"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ createdReject?.(failure);
+ updatedReject?.(failure);
+ }
+ }
+
+ return {
+ adapterId: "openai-realtime",
+ mediaKind: "pcm",
+ async connect() {
+ if (closed || context.signal.aborted) throw Object.assign(new Error("Live call was cancelled"), { errorCode: "LIVE_STALE_CALL" });
+ const url = realtimeUrl(baseUrl, binding.modelId);
+ const liveSocket = await openLiveWebSocket({ url, headers: { Authorization: `Bearer ${apiKey}`, ...(binding.wireProfile === "realtime-compat-v1" ? { "OpenAI-Beta": "realtime=v1" } : {}) }, signal: context.signal, endpointOrigin: "user" });
+ socket = liveSocket;
+ liveSocket.on("message", onSocketMessage);
+ liveSocket.once("close", () => { if (!closed) context.onEvent({ kind: "error", code: "LIVE_NETWORK_ERROR" }); });
+ liveSocket.once("error", () => { if (!closed) context.onEvent({ kind: "error", code: "LIVE_NETWORK_ERROR" }); });
+ await waitForSocketReady(liveSocket, context.signal);
+ await waitForReady(created, context.signal, 12_000, "Realtime session creation timed out");
+ await waitForReady(updated, context.signal, 12_000, "Realtime session update timed out");
+ return {};
+ },
+ sendInputPcm(bytes) {
+ if (closed || !configured || muted || !socket || socket.readyState !== WebSocket.OPEN) return;
+ if (bytes.byteLength < 2 || bytes.byteLength > MAX_FRAME_BYTES || bytes.byteLength > MAX_LIVE_AUDIO_BYTES || bytes.byteLength % 2 !== 0) {
+ throw Object.assign(new Error("Realtime audio frame is invalid"), { errorCode: "LIVE_AUDIO_BACKPRESSURE" });
+ }
+ sendJsonBounded(socket, realtimeAudioMessage(bytes));
+ },
+ async setInputMuted(nextMuted) {
+ muted = nextMuted;
+ },
+ async interrupt(cursors?: LivePlaybackCursor[]) {
+ if (!socket || socket.readyState !== WebSocket.OPEN) return;
+ if (responseTracker.shouldSendCancel()) sendJsonBounded(socket, { type: "response.cancel" });
+ for (const cursor of cursors ?? []) {
+ const messages = realtimeTruncateMessages({ itemId: cursor.itemId, contentIndex: cursor.contentIndex, audioEndMs: cursor.playedSamples * 1000 / cursor.sampleRate });
+ // Local playback is already stopped; send the measured interruption cursor upstream.
+ sendJsonBounded(socket, messages[1]);
+ }
+ },
+ async close() {
+ if (closed) return;
+ closed = true;
+ createdReject?.(new Error("Realtime call closed"));
+ updatedReject?.(new Error("Realtime call closed"));
+ responseTracker.clear();
+ rejectedFunctionCalls.clear();
+ if (socket && socket.readyState !== WebSocket.CLOSED) socket.close(1000, "call ended");
+ socket = null;
+ },
+ };
+}
diff --git a/apps/desktop/electron/main/live-voice/owner.ts b/apps/desktop/electron/main/live-voice/owner.ts
new file mode 100644
index 000000000..dca5af176
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/owner.ts
@@ -0,0 +1,66 @@
+import type { BrowserWindow, IpcMainInvokeEvent, WebFrameMain } from "electron";
+import { fileURLToPath } from "node:url";
+import { resolve } from "node:path";
+import type { WebContents } from "electron";
+import type { LiveOwner } from "./call-service";
+
+export function liveOwnerFromInvoke(event: IpcMainInvokeEvent, mainWindow: BrowserWindow | null): LiveOwner {
+ const frame = event.senderFrame;
+ if (
+ !mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed() ||
+ event.sender !== mainWindow.webContents || !frame || frame !== event.sender.mainFrame ||
+ frame !== mainWindow.webContents.mainFrame || frame.url !== event.sender.getURL() ||
+ !isTrustedRendererUrl(frame.url)
+ ) {
+ throw Object.assign(new Error("Live Voice is available only in the trusted main window"), { errorCode: "LIVE_INVALID_OWNER" });
+ }
+ return {
+ webContentsId: event.sender.id,
+ frameProcessId: frame.processId,
+ frameRoutingId: frame.routingId,
+ url: frame.url,
+ };
+}
+
+export function liveOwnerFrame(mainWindow: BrowserWindow | null, owner: LiveOwner): WebFrameMain | null {
+ if (!mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed()) return null;
+ const frame = mainWindow.webContents.mainFrame;
+ if (
+ mainWindow.webContents.id !== owner.webContentsId ||
+ frame.processId !== owner.frameProcessId ||
+ frame.routingId !== owner.frameRoutingId ||
+ frame.url !== mainWindow.webContents.getURL() ||
+ !isTrustedRendererUrl(frame.url)
+ ) return null;
+ return frame;
+}
+
+export function liveOwnerFromWebContents(mainWindow: BrowserWindow | null, contents: WebContents): LiveOwner | null {
+ if (!mainWindow || mainWindow.isDestroyed() || mainWindow.webContents.isDestroyed() || contents !== mainWindow.webContents || contents.isDestroyed()) return null;
+ const frame = contents.mainFrame;
+ if (frame.url !== contents.getURL() || !isTrustedRendererUrl(frame.url)) return null;
+ return {
+ webContentsId: contents.id,
+ frameProcessId: frame.processId,
+ frameRoutingId: frame.routingId,
+ url: frame.url,
+ };
+}
+
+export function isTrustedRendererUrl(value: string): boolean {
+ try {
+ const url = new URL(value);
+ if (url.protocol === "file:") {
+ if (url.search || url.hash) return false;
+ return resolve(fileURLToPath(url)) === resolve(__dirname, "../../renderer/index.html");
+ }
+ if (url.protocol !== "http:") return false;
+ const configured = process.env.ELECTRON_RENDERER_URL;
+ if (!configured) return false;
+ const expected = new URL(configured);
+ return expected.protocol === "http:" && !expected.username && !expected.password &&
+ url.origin === expected.origin && url.pathname === expected.pathname && !url.username && !url.password;
+ } catch {
+ return false;
+ }
+}
diff --git a/apps/desktop/electron/main/live-voice/runtime.ts b/apps/desktop/electron/main/live-voice/runtime.ts
new file mode 100644
index 000000000..2e966b006
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/runtime.ts
@@ -0,0 +1,105 @@
+import { net, type BrowserWindow, type WebContents } from "electron";
+import { IPC, type AppSettings } from "@pi-desktop/shared";
+import type { VendorOAuth } from "../oauth";
+import type { HostProcess } from "../host-process";
+import { LiveCallService } from "./call-service";
+import { LiveAuthResolver } from "./auth-resolver";
+import { createLivePcmBridge } from "./audio-port";
+import { createCodexAdapter } from "./codex-adapter";
+import { createGeminiAdapter } from "./gemini-adapter";
+import { createOpenAIRealtimeAdapter } from "./openai-realtime-adapter";
+import { liveOwnerFrame } from "./owner";
+import { assertLiveHttpsEndpoint } from "./websocket-transport";
+import type { MicrophoneLeaseRegistry } from "./microphone-lease";
+import type { LiveOwner } from "./call-service";
+
+type BackgroundLease = { webContents: WebContents; previous: boolean; count: number };
+
+export function createLiveCallService(input: {
+ getHost: () => HostProcess | null;
+ getMainWindow: () => BrowserWindow | null;
+ vendorOAuth: Pick<VendorOAuth, "resolveAuth">;
+ microphoneLeases: MicrophoneLeaseRegistry;
+}): LiveCallService {
+ const backgroundLeases = new Map<number, BackgroundLease>();
+ const authResolver = new LiveAuthResolver({
+ callHost: <T,>(method: string, params?: unknown): Promise<T> => {
+ const host = input.getHost();
+ if (!host) return Promise.reject(Object.assign(new Error("host unavailable"), { errorCode: "LIVE_PROVIDER_NOT_FOUND" }));
+ return host.call<T>(method, params);
+ },
+ vendorOAuth: input.vendorOAuth,
+ });
+
+ return new LiveCallService({
+ loadSettings: async () => {
+ const host = input.getHost();
+ if (!host) throw Object.assign(new Error("host unavailable"), { errorCode: "LIVE_PROVIDER_NOT_FOUND" });
+ return host.call<AppSettings>("settings.get");
+ },
+ authResolver,
+ createAdapter: (context) => {
+ switch (context.binding.adapterId) {
+ case "codex-live":
+ return createCodexAdapter(context, {
+ fetchImpl: (url, init) => net.fetch(url instanceof URL ? url.toString() : url, init),
+ assertEndpoint: (url) => assertLiveHttpsEndpoint(url, "third-party"),
+ });
+ case "gemini-live":
+ return createGeminiAdapter(context);
+ case "openai-realtime":
+ return createOpenAIRealtimeAdapter(context);
+ }
+ },
+ createPcmBridge: (bridgeInput) => {
+ const frame = liveOwnerFrame(input.getMainWindow(), bridgeInput.owner);
+ if (!frame) throw Object.assign(new Error("Live Voice owner frame is unavailable"), { errorCode: "LIVE_INVALID_OWNER" });
+ return createLivePcmBridge({
+ ...bridgeInput,
+ ownerFrame: frame,
+ });
+ },
+ sendView: (owner, view) => sendToOwner(input.getMainWindow(), owner, IPC.event.liveVoiceChanged, view),
+ sendControl: (owner, event) => sendToOwner(input.getMainWindow(), owner, IPC.event.liveVoiceControl, event),
+ sendTranscript: (owner, event) => sendToOwner(input.getMainWindow(), owner, IPC.event.liveVoiceTranscript, event),
+ ownerAlive: (owner) => liveOwnerFrame(input.getMainWindow(), owner) !== null,
+ acquireMicrophone: (callId) => input.microphoneLeases.acquire("live", callId),
+ acquireBackgroundThrottlingLease: (callId) => acquireBackgroundLease(input.getMainWindow(), callId, backgroundLeases),
+ });
+}
+
+function sendToOwner(window: BrowserWindow | null, owner: LiveOwner, channel: string, payload: unknown): void {
+ const frame = liveOwnerFrame(window, owner);
+ if (!frame || !window || window.isDestroyed()) return;
+ frame.send(channel, payload);
+}
+
+function acquireBackgroundLease(
+ window: BrowserWindow | null,
+ _callId: string,
+ leases: Map<number, BackgroundLease>,
+): () => void {
+ if (!window || window.isDestroyed() || window.webContents.isDestroyed()) {
+ throw Object.assign(new Error("Live Voice owner window is unavailable"), { errorCode: "LIVE_INVALID_OWNER" });
+ }
+ const contents = window.webContents;
+ let lease = leases.get(contents.id);
+ if (!lease) {
+ const previous = contents.getBackgroundThrottling();
+ lease = { webContents: contents, previous, count: 0 };
+ leases.set(contents.id, lease);
+ contents.setBackgroundThrottling(false);
+ }
+ lease.count += 1;
+ let released = false;
+ return () => {
+ if (released) return;
+ released = true;
+ const current = leases.get(contents.id);
+ if (current !== lease) return;
+ current.count -= 1;
+ if (current.count > 0) return;
+ leases.delete(contents.id);
+ if (!contents.isDestroyed()) contents.setBackgroundThrottling(current.previous);
+ };
+}
diff --git a/apps/desktop/electron/main/live-voice/types.ts b/apps/desktop/electron/main/live-voice/types.ts
new file mode 100644
index 000000000..b09157f79
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/types.ts
@@ -0,0 +1,45 @@
+import type { LiveBinding, LiveEndReason, LivePlaybackCursor, LiveRealtimeWireProfile } from "@pi-desktop/shared";
+import type { ProviderPublic } from "@pi-desktop/shared";
+import type { ModelAuth } from "@earendil-works/pi-ai";
+import type { LiveWireEvent } from "@pi-desktop/voice-runtime/live";
+
+export type LiveResolvedProvider = {
+ provider: ProviderPublic;
+ secret?: string;
+};
+
+export type LiveResolvedAuth =
+ | { kind: "codex-oauth"; accessToken: string; accountId: string }
+ | { kind: "api-key"; apiKey: string; baseUrl: string };
+
+export type LiveAdapterContext = {
+ callId: string;
+ binding: Readonly<LiveBinding>;
+ provider: ProviderPublic;
+ auth: LiveResolvedAuth;
+ signal: AbortSignal;
+ onEvent: (event: LiveWireEvent) => void;
+};
+
+export type { LivePlaybackCursor } from "@pi-desktop/shared";
+
+export type LiveAdapter = {
+ readonly adapterId: LiveBinding["adapterId"];
+ readonly mediaKind: "webrtc" | "pcm";
+ connect(input?: { offerSdp?: string }): Promise<{ answerSdp?: string }>;
+ sendInputPcm?(bytes: Uint8Array): void;
+ setInputMuted?(muted: boolean): Promise<void>;
+ interrupt?(cursors?: LivePlaybackCursor[]): Promise<void>;
+ rejectDelegation?(input: { callId: string; delegationId: string }): Promise<void>;
+ close(reason: LiveEndReason): Promise<void>;
+};
+
+export type LiveAdapterFactory = (context: LiveAdapterContext) => LiveAdapter;
+
+export type LiveProviderDescriptor = {
+ auth: LiveResolvedAuth;
+ provider: ProviderPublic;
+};
+
+export type CodexModelAuth = ModelAuth;
+export type LiveBindingProfile = LiveRealtimeWireProfile;
diff --git a/apps/desktop/electron/main/live-voice/websocket-errors.ts b/apps/desktop/electron/main/live-voice/websocket-errors.ts
new file mode 100644
index 000000000..32db45072
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/websocket-errors.ts
@@ -0,0 +1,7 @@
+export function responseCodeError(status: number): { code: string; retriable: boolean } {
+ if (status === 401) return { code: "LIVE_AUTH_REQUIRED", retriable: false };
+ if (status === 403) return { code: "LIVE_ACCESS_DENIED", retriable: false };
+ if (status === 429) return { code: "LIVE_RATE_LIMITED", retriable: true };
+ if (status === 404 || status === 426) return { code: "LIVE_PROTOCOL_UNSUPPORTED", retriable: false };
+ return { code: "LIVE_NETWORK_ERROR", retriable: status >= 500 };
+}
diff --git a/apps/desktop/electron/main/live-voice/websocket-transport.ts b/apps/desktop/electron/main/live-voice/websocket-transport.ts
new file mode 100644
index 000000000..e4f0c2dc5
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/websocket-transport.ts
@@ -0,0 +1,156 @@
+import { connectViaProxy } from "@pi-desktop/agent-runtime/proxy-tunnel";
+import { parseProxyUrl, type ParsedProxyUrl } from "@pi-desktop/shared";
+import { Agent as HttpsAgent } from "node:https";
+import { Duplex } from "node:stream";
+import { connect as tlsConnect } from "node:tls";
+import { net, session } from "electron";
+import { WebSocket } from "ws";
+import { allowInsecureUserEndpointsEnabled, noteInsecureUserEndpoint, relaxedNetworkPolicyEnabled } from "../endpoint-policy";
+import { createPublicHttpsClient } from "../public-https-fetch";
+import { responseCodeError } from "./websocket-errors";
+
+const HANDSHAKE_TIMEOUT_MS = 15_000;
+const SOCKET_MAX_PAYLOAD = 2 * 1024 * 1024;
+
+const endpointGuard = createPublicHttpsClient({
+ fetchImpl: (url, init) => net.fetch(url, init),
+ routeImpl: (url) => session.defaultSession.resolveProxy(url),
+ allowFakeIp: () => relaxedNetworkPolicyEnabled(),
+ allowInsecureUserEndpoints: () => allowInsecureUserEndpointsEnabled(),
+ onInsecureUserEndpoint: (host) => noteInsecureUserEndpoint(host),
+});
+
+class ProxyTunnelAgent extends HttpsAgent {
+ constructor(private readonly proxy: ParsedProxyUrl) {
+ super({ keepAlive: false });
+ }
+
+ override createConnection(
+ options: Parameters<HttpsAgent["createConnection"]>[0],
+ callback?: (error: Error | null, socket: Duplex) => void,
+ ): Duplex | null | undefined {
+ const host = options.hostname ?? options.host ?? "";
+ const port = Number(options.port) || 443;
+ const servername = options.servername ?? host;
+ if (!callback) throw new Error("proxy tunnel requires a socket callback");
+ void connectViaProxy(this.proxy, host, port)
+ .then((socket) => {
+ const secure = tlsConnect({ socket, host, servername, ALPNProtocols: ["http/1.1"] });
+ secure.once("secureConnect", () => callback(null, secure));
+ secure.once("error", (error) => callback(error, secure));
+ })
+ .catch((error: unknown) => {
+ const failure = error instanceof Error ? error : new Error("proxy tunnel failed");
+ const unavailable = new Duplex({ read() {}, write(_chunk, _encoding, done) { done(failure); } });
+ callback(failure, unavailable);
+ });
+ return null;
+ }
+}
+
+function parseResolvedProxy(route: string): ParsedProxyUrl | null {
+ const steps = route.split(";").map((item) => item.trim()).filter(Boolean);
+ if (steps.length !== 1) {
+ throw Object.assign(new Error("network proxy route cannot be honored by the Live transport"), {
+ errorCode: "LIVE_NETWORK_POLICY_UNSUPPORTED",
+ });
+ }
+ const directive = steps[0];
+ if (directive.toUpperCase() === "DIRECT") return null;
+ const match = directive.match(/^(PROXY|HTTP|HTTPS|SOCKS5)\s+(.+)$/i);
+ if (!match) {
+ throw Object.assign(new Error("network proxy route cannot be honored by the Live transport"), {
+ errorCode: "LIVE_NETWORK_POLICY_UNSUPPORTED",
+ });
+ }
+ const scheme = match[1].toUpperCase() === "HTTPS" ? "https" : match[1].toUpperCase() === "SOCKS5" ? "socks5" : "http";
+ const parsed = parseProxyUrl(`${scheme}://${match[2]}`);
+ if (!parsed.ok) {
+ throw Object.assign(new Error("network proxy route is invalid"), {
+ errorCode: "LIVE_NETWORK_POLICY_UNSUPPORTED",
+ });
+ }
+ return parsed.value;
+}
+
+export async function openLiveWebSocket(input: {
+ url: string;
+ headers?: Record<string, string>;
+ signal: AbortSignal;
+ endpointOrigin: "user" | "third-party";
+}): Promise<WebSocket> {
+ const parsedUrl = new URL(input.url);
+ if (parsedUrl.protocol !== "wss:") {
+ throw Object.assign(new Error("Live WebSocket endpoints must use TLS"), {
+ errorCode: "LIVE_NETWORK_POLICY_UNSUPPORTED",
+ });
+ }
+ await endpointGuard.assertPublicUrl(input.url.replace(/^wss:/, "https:"), input.endpointOrigin);
+ if (input.signal.aborted) throw input.signal.reason;
+ const route = await session.defaultSession.resolveProxy(input.url);
+ const proxy = parseResolvedProxy(route);
+ const agent = proxy ? new ProxyTunnelAgent(proxy) : undefined;
+
+ try {
+ const connected = await new Promise<WebSocket>((resolve, reject) => {
+ const socket = new WebSocket(input.url, {
+ ...(agent ? { agent } : {}),
+ ...(input.headers ? { headers: input.headers } : {}),
+ maxPayload: SOCKET_MAX_PAYLOAD,
+ handshakeTimeout: HANDSHAKE_TIMEOUT_MS,
+ followRedirects: false,
+ perMessageDeflate: false,
+ });
+ let settled = false;
+ const onAbort = () => {
+ socket.terminate();
+ if (!settled) {
+ settled = true;
+ reject(input.signal.reason);
+ }
+ };
+ const cleanup = () => input.signal.removeEventListener("abort", onAbort);
+ input.signal.addEventListener("abort", onAbort, { once: true });
+ socket.once("open", () => {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ resolve(socket);
+ });
+ socket.once("error", (error) => {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ socket.terminate();
+ reject(Object.assign(new Error("Live provider connection failed"), { cause: error }));
+ });
+ socket.once("close", () => {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ reject(new Error("Live provider closed during handshake"));
+ });
+ socket.once("unexpected-response", (_request, response) => {
+ if (settled) return;
+ settled = true;
+ cleanup();
+ socket.terminate();
+ response.destroy();
+ const mapped = responseCodeError(response.statusCode ?? 0);
+ reject(Object.assign(new Error("Live provider rejected the WebSocket handshake"), {
+ errorCode: mapped.code,
+ retriable: mapped.retriable,
+ }));
+ });
+ });
+ connected.once("close", () => agent?.destroy());
+ return connected;
+ } catch (error) {
+ agent?.destroy();
+ throw error;
+ }
+}
+
+export async function assertLiveHttpsEndpoint(url: string, origin: "user" | "third-party"): Promise<void> {
+ await endpointGuard.assertPublicUrl(url, origin);
+}
diff --git a/apps/desktop/electron/main/live-voice/websocket-wire.ts b/apps/desktop/electron/main/live-voice/websocket-wire.ts
new file mode 100644
index 000000000..0605ea054
--- /dev/null
+++ b/apps/desktop/electron/main/live-voice/websocket-wire.ts
@@ -0,0 +1,79 @@
+import { MAX_LIVE_JSON_BYTES } from "@pi-desktop/voice-runtime/live";
+import { WebSocket } from "ws";
+
+const MAX_BUFFERED_JSON_BYTES = 128 * 1024;
+const SOCKET_READY_TIMEOUT_MS = 15_000;
+
+export function websocketJson(data: unknown, maxBytes = MAX_LIVE_JSON_BYTES): unknown {
+ let text: string;
+ if (typeof data === "string") text = data;
+ else if (Buffer.isBuffer(data)) text = data.toString("utf8");
+ else if (data instanceof ArrayBuffer) text = Buffer.from(data).toString("utf8");
+ else if (ArrayBuffer.isView(data)) text = Buffer.from(data.buffer, data.byteOffset, data.byteLength).toString("utf8");
+ else throw new Error("Live provider sent a non-text event");
+ if (Buffer.byteLength(text, "utf8") > maxBytes) throw new Error("Live provider event exceeded the size limit");
+ return JSON.parse(text) as unknown;
+}
+
+export function sendJsonBounded(socket: WebSocket, value: unknown): void {
+ const body = JSON.stringify(value);
+ const byteLength = Buffer.byteLength(body, "utf8");
+ if (byteLength > MAX_LIVE_JSON_BYTES || socket.bufferedAmount + byteLength > MAX_BUFFERED_JSON_BYTES) {
+ throw Object.assign(new Error("Live audio transport queue is full"), { errorCode: "LIVE_AUDIO_BACKPRESSURE" });
+ }
+ socket.send(body, (error) => {
+ if (error) socket.terminate();
+ });
+}
+
+export async function waitForSocketReady(socket: WebSocket, signal: AbortSignal): Promise<void> {
+ if (socket.readyState === WebSocket.OPEN) return;
+ await new Promise<void>((resolve, reject) => {
+ const timeout = setTimeout(() => finish(Object.assign(new Error("Live provider socket timed out"), { errorCode: "LIVE_TIMEOUT" })), SOCKET_READY_TIMEOUT_MS);
+ const onOpen = () => finish();
+ const onError = () => finish(Object.assign(new Error("Live provider socket failed"), { errorCode: "LIVE_NETWORK_ERROR" }));
+ const onClose = () => finish(Object.assign(new Error("Live provider closed during handshake"), { errorCode: "LIVE_NETWORK_ERROR" }));
+ const onAbort = () => finish(Object.assign(new Error("Live provider connection was cancelled"), { errorCode: "LIVE_STALE_CALL" }));
+ function cleanup(): void {
+ clearTimeout(timeout);
+ socket.off("open", onOpen);
+ socket.off("error", onError);
+ socket.off("close", onClose);
+ signal.removeEventListener("abort", onAbort);
+ }
+ function finish(error?: Error): void {
+ cleanup();
+ if (error) reject(error);
+ else resolve();
+ }
+ if (signal.aborted) return onAbort();
+ socket.once("open", onOpen);
+ socket.once("error", onError);
+ socket.once("close", onClose);
+ signal.addEventListener("abort", onAbort, { once: true });
+ });
+}
+
+export async function waitForReady(
+ promise: Promise<void>,
+ signal: AbortSignal,
+ timeoutMs: number,
+ message: string,
+): Promise<void> {
+ if (signal.aborted) throw Object.assign(new Error("Live setup was cancelled"), { errorCode: "LIVE_STALE_CALL" });
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ let abortListener: (() => void) | undefined;
+ const aborted = new Promise<never>((_, reject) => {
+ abortListener = () => reject(Object.assign(new Error("Live setup was cancelled"), { errorCode: "LIVE_STALE_CALL" }));
+ signal.addEventListener("abort", abortListener, { once: true });
+ });
+ const timeout = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(Object.assign(new Error(message), { errorCode: "LIVE_TIMEOUT" })), timeoutMs);
+ });
+ try {
+ await Promise.race([promise, aborted, timeout]);
+ } finally {
+ if (timer) clearTimeout(timer);
+ if (abortListener) signal.removeEventListener("abort", abortListener);
+ }
+}
diff --git a/apps/desktop/electron/main/voice-service.ts b/apps/desktop/electron/main/voice-service.ts
index 8acd76fa1..b34c6a477 100644
--- a/apps/desktop/electron/main/voice-service.ts
+++ b/apps/desktop/electron/main/voice-service.ts
@@ -6,6 +6,7 @@
*/
import { app, BrowserWindow } from "electron";
+import { randomUUID } from "node:crypto";
import { PvRecorderBackend, checkMicrophonePermission, requestMicrophonePermission } from "./audio-backend";
import type {
AudioCaptureFactory,
@@ -28,10 +29,12 @@ export class VoiceService {
private captureFactory: AudioCaptureFactory;
private settings: VoiceSettings;
private disposed = false;
+ private releaseMicrophoneLease: (() => void) | null = null;
constructor(
private readonly modelCacheDir: string,
private readonly getWindow: () => BrowserWindow | null,
+ private readonly acquireMicrophoneLease: (token: string) => () => void = () => () => undefined,
) {
this.captureFactory = new PvRecorderBackend();
// Will be overridden from app settings
@@ -76,6 +79,9 @@ export class VoiceService {
// Forward state changes to renderer
this.controller.on("stateChange", (state: VoiceState) => {
this.sendToRenderer("voice:stateChanged", state);
+ if (state.phase === "done" || state.phase === "error" || state.phase === "idle") {
+ this.releaseCurrentMicrophoneLease();
+ }
});
}
@@ -89,16 +95,28 @@ export class VoiceService {
}
await this.ensureRuntime();
- await this.controller!.start();
+ this.releaseCurrentMicrophoneLease();
+ this.releaseMicrophoneLease = this.acquireMicrophoneLease(randomUUID());
+ try {
+ await this.controller!.start();
+ } catch (error) {
+ this.releaseCurrentMicrophoneLease();
+ throw error;
+ }
}
async stop(): Promise<VoiceResult> {
if (!this.controller) throw new Error("Voice not started");
- return this.controller.stop();
+ try {
+ return await this.controller.stop();
+ } finally {
+ this.releaseCurrentMicrophoneLease();
+ }
}
cancel(): void {
this.controller?.cancel();
+ this.releaseCurrentMicrophoneLease();
}
getState(): VoiceState {
@@ -152,6 +170,7 @@ export class VoiceService {
if (this.disposed) return;
this.disposed = true;
this.controller?.dispose();
+ this.releaseCurrentMicrophoneLease();
this.engine?.shutdown();
this.controller = null;
this.engine = null;
@@ -170,13 +189,19 @@ export class VoiceService {
// Window may be closing
}
}
+
+ private releaseCurrentMicrophoneLease(): void {
+ this.releaseMicrophoneLease?.();
+ this.releaseMicrophoneLease = null;
+ }
}
export function createVoiceService(
modelCacheDir: string,
getWindow: () => BrowserWindow | null,
+ acquireMicrophoneLease?: (token: string) => () => void,
): VoiceService {
- const service = new VoiceService(modelCacheDir, getWindow);
+ const service = new VoiceService(modelCacheDir, getWindow, acquireMicrophoneLease);
app.once("before-quit", () => service.dispose());
return service;
}
diff --git a/apps/desktop/electron/preload/index.ts b/apps/desktop/electron/preload/index.ts
index b947b6dc9..591b5aafe 100644
--- a/apps/desktop/electron/preload/index.ts
+++ b/apps/desktop/electron/preload/index.ts
@@ -27,6 +27,16 @@ const api = {
ipcRenderer.on(channel, wrapped);
return () => ipcRenderer.removeListener(channel, wrapped);
},
+ onLiveVoicePort: () => {
+ const listener = (event: Electron.IpcRendererEvent, payload: unknown) => {
+ const value = payload && typeof payload === "object" ? payload as { callId?: unknown; nonce?: unknown } : null;
+ const port = event.ports[0];
+ if (!port || typeof value?.callId !== "string" || typeof value.nonce !== "string") return;
+ window.postMessage({ kind: "pi-desktop-live-voice-port", callId: value.callId, nonce: value.nonce }, "*", [port]);
+ };
+ ipcRenderer.on(IPC.event.liveVoicePort, listener);
+ return () => ipcRenderer.removeListener(IPC.event.liveVoicePort, listener);
+ },
channels: IPC,
// Synchronous platform info so the renderer can style window chrome
// (traffic lights on macOS vs. controls overlay on Windows/Linux)
diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
index 09b4315cf..9633efa96 100644
--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx
@@ -20,6 +20,7 @@ import {
} from "../../../components/icons";
import { ModeIcon } from "./ComposerModeIcon";
import { VoiceMicButton } from "../../voice/VoiceMicButton";
+import { LiveVoiceControls } from "../../voice/live/LiveVoiceControls";
import { ComposerModelPicker } from "./ComposerModelPicker";
import {
MODE_LABEL_KEYS,
@@ -134,6 +135,7 @@ export function ComposerToolbar({
onCancel={onVoiceCancel}
/>
)}
+ <LiveVoiceControls t={t} />
<TooltipButton
type="button"
className="icon-btn mode-chip composer-mode-chip"
diff --git a/apps/desktop/src/features/settings/voice/LiveVoiceSettings.tsx b/apps/desktop/src/features/settings/voice/LiveVoiceSettings.tsx
new file mode 100644
index 000000000..ade79bba5
--- /dev/null
+++ b/apps/desktop/src/features/settings/voice/LiveVoiceSettings.tsx
@@ -0,0 +1,211 @@
+import { useEffect, useMemo, useState } from "react";
+import { useSyncExternalStore } from "react";
+import type { TFunction } from "i18next";
+import type { AppSettings, LiveBinding, LiveVoiceSettings, ProviderPublic } from "@pi-desktop/shared";
+import { OAUTH_AUTH_KIND } from "@pi-desktop/shared";
+import { Badge, Input, SettingsToggle } from "../../../components/ui";
+import { SettingsMenuSelect } from "../../../components/settings/SettingsMenuSelect";
+import { SettingsCard, SettingsRow } from "../primitives";
+import { api } from "../../../lib/api";
+import { getLiveCallController } from "../../voice/live/live-call-controller";
+
+type Adapter = LiveBinding["adapterId"];
+
+export function LiveVoiceSettings({
+ t,
+ settings,
+ saveSettings,
+}: {
+ t: TFunction;
+ settings: AppSettings;
+ saveSettings: (patch: Partial<AppSettings>) => Promise<void>;
+}) {
+ const live: LiveVoiceSettings = settings.liveVoice ?? { enabled: false, bindings: [] };
+ const controller = getLiveCallController();
+ const liveSnapshot = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
+ const [providers, setProviders] = useState<ProviderPublic[]>([]);
+ const [saving, setSaving] = useState(false);
+ const [saveFailed, setSaveFailed] = useState(false);
+ const [drafts, setDrafts] = useState<Record<string, { modelId?: string; voice?: string }>>({});
+ const bindingByAdapter = useMemo(() => {
+ const result = new Map<Adapter, LiveBinding>();
+ for (const binding of live.bindings) if (!result.has(binding.adapterId)) result.set(binding.adapterId, binding);
+ return result;
+ }, [live.bindings]);
+
+ useEffect(() => {
+ let cancelled = false;
+ void api.listProviders().then((result) => {
+ if (!cancelled) setProviders(result.providers);
+ }).catch(() => {
+ if (!cancelled) setProviders([]);
+ });
+ return () => { cancelled = true; };
+ }, []);
+
+ const providerChoices = (adapter: Adapter) => providers.filter((provider) => {
+ if (adapter === "codex-live") return provider.vendorKey === "openai-codex" && provider.authKind === OAUTH_AUTH_KIND;
+ if (provider.authKind === OAUTH_AUTH_KIND) return false;
+ if (adapter === "gemini-live") return provider.vendorKey === "google" && provider.apiStyle === "google_generative_ai";
+ return Boolean(provider.baseUrl);
+ });
+
+ const save = async (next: LiveVoiceSettings) => {
+ setSaving(true);
+ setSaveFailed(false);
+ try {
+ await saveSettings({ liveVoice: next });
+ await controller.refreshStatus();
+ } catch {
+ setSaveFailed(true);
+ } finally {
+ setSaving(false);
+ }
+ };
+
+ const updateBinding = (adapter: Adapter, patch: Record<string, string>): Promise<void> => {
+ const current = bindingByAdapter.get(adapter);
+ const providerId = patch.providerId ?? current?.providerId;
+ if (!providerId) return Promise.resolve();
+ const id = current?.id ?? `live-${adapter}-${crypto.randomUUID()}`;
+ const currentModel = current && "modelId" in current ? current.modelId : undefined;
+ const nextBinding: LiveBinding = adapter === "codex-live"
+ ? { id, adapterId: adapter, providerId, voice: patch.voice ?? (current?.voice || "cove") }
+ : adapter === "gemini-live"
+ ? { id, adapterId: adapter, providerId, modelId: patch.modelId ?? (currentModel || "gemini-3.8-live"), voice: patch.voice ?? (current?.voice || "Kore") }
+ : {
+ id,
+ adapterId: adapter,
+ providerId,
+ modelId: patch.modelId ?? (currentModel || "gpt-realtime-2.1"),
+ voice: patch.voice ?? (current?.voice || "marin"),
+ wireProfile: patch.wireProfile === "realtime-compat-v1" ? "realtime-compat-v1" : current?.adapterId === "openai-realtime" ? current.wireProfile : "realtime-ga",
+ };
+ const bindings = current
+ ? live.bindings.map((binding) => binding.id === current.id ? nextBinding : binding)
+ : [...live.bindings, nextBinding];
+ return save({ ...live, bindings, selectedBindingId: patch.providerId ? id : live.selectedBindingId ?? id });
+ };
+
+ const removeBinding = (adapter: Adapter) => {
+ const current = bindingByAdapter.get(adapter);
+ if (!current) return;
+ const bindings = live.bindings.filter((binding) => binding.id !== current.id);
+ const selectedBindingId = live.selectedBindingId === current.id ? bindings[0]?.id : live.selectedBindingId;
+ void save({ enabled: live.enabled, bindings, ...(selectedBindingId ? { selectedBindingId } : {}) });
+ };
+
+ const selected = liveSnapshot.call;
+ const adapterLocked = (adapter: Adapter) => Boolean(selected && selected.bindingId === bindingByAdapter.get(adapter)?.id && !["ended", "failed"].includes(selected.phase));
+ const providerLabel = (provider: ProviderPublic) => `${provider.name}${provider.enabled ? "" : ` · ${t("liveVoice.providerDisabled")}`}${provider.hasSecret ? "" : ` · ${t("liveVoice.credentialsMissing")}`}`;
+
+ const renderAdapter = (adapter: Adapter) => {
+ const current = bindingByAdapter.get(adapter);
+ const choices = providerChoices(adapter);
+ const readiness = current && liveSnapshot.status?.bindings.find((item) => item.bindingId === current.id);
+ const locked = adapterLocked(adapter);
+ const title = t(`liveVoice.adapters.${adapter}.title`);
+ return (
+ <SettingsCard key={adapter} title={title} description={t(`liveVoice.adapters.${adapter}.description`)}>
+ {current && readiness ? (
+ <SettingsRow title={t("liveVoice.bindingStatus")}>
+ <Badge tone={readiness.selectable ? "success" : "warning"}>
+ {readiness.selectable ? t("liveVoice.ready") : t(`liveVoice.readiness.${readiness.reason ?? "missing-provider"}`)}
+ </Badge>
+ </SettingsRow>
+ ) : null}
+ <SettingsRow title={t("liveVoice.provider")}>
+ <SettingsMenuSelect
+ value={current?.providerId ?? ""}
+ label={t("liveVoice.provider")}
+ disabled={saving || locked}
+ options={[
+ { id: "", label: t("liveVoice.chooseProvider") },
+ ...choices.map((provider) => ({ id: provider.id, label: providerLabel(provider) })),
+ ...(current && !choices.some((item) => item.id === current.providerId)
+ ? [{ id: current.providerId, label: t("liveVoice.providerUnavailable") }]
+ : []),
+ ]}
+ onChange={(providerId) => providerId ? void updateBinding(adapter, { providerId }) : removeBinding(adapter)}
+ />
+ </SettingsRow>
+ {current ? (
+ <SettingsRow title={t("liveVoice.useForNextCall")}>
+ <SettingsToggle
+ checked={live.selectedBindingId === current.id}
+ label={t("liveVoice.useForNextCall")}
+ disabled={saving || locked}
+ onChange={() => void save({ ...live, selectedBindingId: current.id })}
+ />
+ </SettingsRow>
+ ) : null}
+ {adapter !== "codex-live" ? (
+ <SettingsRow title={t("liveVoice.model")}>
+ <Input
+ aria-label={t("liveVoice.model")}
+ value={current ? drafts[current.id]?.modelId ?? ("modelId" in current ? current.modelId : "") : ""}
+ disabled={!current || saving || locked}
+ maxLength={160}
+ onChange={(event) => current && setDrafts((all) => ({ ...all, [current.id]: { ...all[current.id], modelId: event.currentTarget.value } }))}
+ onBlur={(event) => {
+ if (!current) return;
+ const modelId = event.currentTarget.value.trim();
+ if (modelId) void updateBinding(adapter, { modelId }).finally(() => setDrafts((all) => { const next = { ...all }; delete next[current.id]; return next; }));
+ else setDrafts((all) => { const next = { ...all }; delete next[current.id]; return next; });
+ }}
+ />
+ </SettingsRow>
+ ) : null}
+ <SettingsRow title={t("liveVoice.voice")}>
+ <Input
+ aria-label={t("liveVoice.voice")}
+ value={current ? drafts[current.id]?.voice ?? current.voice : ""}
+ disabled={!current || saving || locked}
+ maxLength={64}
+ onChange={(event) => current && setDrafts((all) => ({ ...all, [current.id]: { ...all[current.id], voice: event.currentTarget.value } }))}
+ onBlur={(event) => {
+ if (!current) return;
+ const voice = event.currentTarget.value.trim();
+ if (voice) void updateBinding(adapter, { voice }).finally(() => setDrafts((all) => { const next = { ...all }; delete next[current.id]; return next; }));
+ else setDrafts((all) => { const next = { ...all }; delete next[current.id]; return next; });
+ }}
+ />
+ </SettingsRow>
+ {adapter === "openai-realtime" ? (
+ <SettingsRow title={t("liveVoice.profile")}>
+ <SettingsMenuSelect
+ value={current?.adapterId === "openai-realtime" ? current.wireProfile : "realtime-ga"}
+ label={t("liveVoice.profile")}
+ disabled={!current || saving || locked}
+ options={[
+ { id: "realtime-ga", label: t("liveVoice.profiles.realtime-ga") },
+ { id: "realtime-compat-v1", label: t("liveVoice.profiles.realtime-compat-v1") },
+ ]}
+ onChange={(wireProfile) => updateBinding(adapter, { wireProfile })}
+ />
+ </SettingsRow>
+ ) : null}
+ {locked ? <SettingsRow title={t("liveVoice.bindingLocked")}>{t("liveVoice.bindingLockedDetail")}</SettingsRow> : null}
+ </SettingsCard>
+ );
+ };
+
+ return (
+ <div className="settings-stack voice-settings live-voice-settings">
+ <SettingsCard title={t("liveVoice.title")} description={t("liveVoice.description")}>
+ <SettingsRow title={t("liveVoice.enable")} description={t("liveVoice.enableDetail")}>
+ <SettingsToggle
+ checked={live.enabled}
+ label={t("liveVoice.enable")}
+ busy={saving}
+ onChange={() => void save({ ...live, enabled: !live.enabled })}
+ />
+ </SettingsRow>
+ {saveFailed ? <div className="live-voice-error" role="alert">{t("liveVoice.saveFailed")}</div> : null}
+ </SettingsCard>
+ {renderAdapter("codex-live")}
+ {renderAdapter("gemini-live")}
+ {renderAdapter("openai-realtime")}
+ </div>
+ );
+}
diff --git a/apps/desktop/src/features/settings/voice/VoiceSettingsSection.tsx b/apps/desktop/src/features/settings/voice/VoiceSettingsSection.tsx
index 11c36ac0b..0dd399625 100644
--- a/apps/desktop/src/features/settings/voice/VoiceSettingsSection.tsx
+++ b/apps/desktop/src/features/settings/voice/VoiceSettingsSection.tsx
@@ -10,6 +10,7 @@ import { Button, Badge, CheckboxGroup, SettingsToggle } from "../../../component
import { SettingsMenuSelect } from "../../../components/settings/SettingsMenuSelect";
import { SettingsRow, SettingsCard } from "../primitives";
import { voiceIpc } from "../../voice/voice-ipc";
+import { LiveVoiceSettings } from "./LiveVoiceSettings";
interface AudioInputDevice {
deviceId: string;
@@ -122,6 +123,7 @@ export function VoiceSettingsSection({
return (
<div className="settings-stack voice-settings">
+ <LiveVoiceSettings t={t} settings={settings} saveSettings={saveSettings} />
{/* ---- Enable ---- */}
<SettingsCard title={t("settings.voice")}>
<SettingsRow title={t("settings.voiceEnable")}>
diff --git a/apps/desktop/src/features/voice/live/LiveVoiceControls.tsx b/apps/desktop/src/features/voice/live/LiveVoiceControls.tsx
new file mode 100644
index 000000000..e955550ad
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/LiveVoiceControls.tsx
@@ -0,0 +1,127 @@
+import { useEffect, useRef, useState, useSyncExternalStore } from "react";
+import type { TFunction } from "i18next";
+import { Badge, Button, Panel, TooltipButton } from "../../../components/ui";
+import { IconMic } from "../../../components/icons";
+import { getLiveCallController } from "./live-call-controller";
+import "../../../styles/voice.css";
+
+export function LiveVoiceControls({ t }: { t: TFunction }) {
+ const controller = getLiveCallController();
+ const snapshot = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
+ const [open, setOpen] = useState(false);
+ 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");
+
+ 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);
+ triggerRef.current?.focus();
+ };
+ window.addEventListener("keydown", onKeyDown);
+ return () => window.removeEventListener("keydown", onKeyDown);
+ }, [open]);
+
+ const closePanel = () => {
+ setOpen(false);
+ triggerRef.current?.focus();
+ };
+
+ 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>
+ {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}
+ {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>
+ )}
+ <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}
+ </Panel>
+ </div>
+ ) : 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
new file mode 100644
index 000000000..2368189ed
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/live-call-controller.ts
@@ -0,0 +1,631 @@
+import {
+ parseCodexMessage,
+ codexDelegationFeedback,
+} from "@pi-desktop/voice-runtime/live";
+import type {
+ LiveCallView,
+ LiveControlEvent,
+ LiveStatus,
+ LiveTranscriptSegment,
+} from "@pi-desktop/shared";
+import { api } from "../../../lib/api";
+import { liveVoiceApi, liveError } from "./live-voice-api";
+import { LivePcmSession } from "./live-pcm-session";
+import pcmWorkletUrl from "./pcm-worklet.js?url";
+
+export type LiveVoiceSnapshot = {
+ status: LiveStatus | null;
+ call: LiveCallView | null;
+ transcripts: LiveTranscriptSegment[];
+ starting: boolean;
+ errorCode?: string;
+};
+
+const EMPTY_SNAPSHOT: LiveVoiceSnapshot = {
+ status: null,
+ call: null,
+ transcripts: [],
+ starting: false,
+};
+const MAX_TRANSCRIPTS = 40;
+const ICE_GATHER_TIMEOUT_MS = 10_000;
+
+type StartResources = {
+ requestId: string;
+ callId?: string;
+ stream?: MediaStream;
+ context?: AudioContext;
+ port?: MessagePort;
+ pcm?: LivePcmSession;
+ peer?: RTCPeerConnection;
+ channel?: RTCDataChannel;
+ audio?: HTMLAudioElement;
+ heartbeat?: ReturnType<typeof setInterval>;
+ captureEpoch: number;
+ releasePromise?: Promise<void>;
+ abort: AbortController;
+};
+
+/** Window-lifetime owner for Live media. React subscriptions never own it. */
+export class LiveCallController {
+ private snapshot: LiveVoiceSnapshot = EMPTY_SNAPSHOT;
+ private readonly listeners = new Set<() => void>();
+ private readonly resources = new Map<string, StartResources>();
+ private readonly pendingPorts = new Map<string, { port: MessagePort; nonce: string }>();
+ private readonly portWaiters = new Map<string, { nonce: string; resolve: (port: MessagePort) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
+ private readonly disposers: Array<() => void> = [];
+ private readonly terminalCallIds = new Set<string>();
+ private generation = 0;
+ private microphoneDeviceId: string | null = null;
+
+ constructor() {
+ this.disposers.push(
+ liveVoiceApi.onView((view) => this.handleView(view)),
+ liveVoiceApi.onControl((event) => this.handleControl(event)),
+ liveVoiceApi.onTranscript((event) => this.handleTranscript(event.callId, event.segment)),
+ api.onSettingsChanged((patch) => {
+ const voice = patch.voice;
+ if (voice && typeof voice === "object" && "deviceId" in voice) {
+ const deviceId = (voice as { deviceId?: unknown }).deviceId;
+ this.microphoneDeviceId = typeof deviceId === "string" && deviceId ? deviceId : null;
+ }
+ }),
+ );
+ this.disposers.push(window.piDesktop?.onLiveVoicePort?.() ?? (() => undefined));
+ window.addEventListener("message", this.handlePortMessage);
+ window.addEventListener("pagehide", this.handlePageHide, { once: true });
+ void this.refreshStatus();
+ void api.getSettings().then((settings) => {
+ this.microphoneDeviceId = settings.voice?.deviceId ?? null;
+ }).catch(() => undefined);
+ }
+
+ readonly getSnapshot = (): LiveVoiceSnapshot => this.snapshot;
+
+ readonly subscribe = (listener: () => void): (() => void) => {
+ this.listeners.add(listener);
+ return () => this.listeners.delete(listener);
+ };
+
+ async refreshStatus(): Promise<void> {
+ try {
+ const status = await liveVoiceApi.status();
+ this.patch({ status });
+ } catch (error) {
+ this.patch({ errorCode: errorCode(error) });
+ }
+ }
+
+ async start(): Promise<void> {
+ if (this.snapshot.starting || isLive(this.snapshot.call?.phase)) return;
+ const generation = ++this.generation;
+ const cachedStatus = this.snapshot.status;
+ if (!cachedStatus?.enabled) throw liveError("LIVE_DISABLED");
+ const selectedId = cachedStatus.selectedBindingId;
+ const selected = cachedStatus.bindings.find((item) => item.bindingId === selectedId && item.selectable);
+ if (!selected) throw liveError("LIVE_NOT_CONFIGURED");
+
+ const requestId = crypto.randomUUID();
+ const resources: StartResources = { requestId, abort: new AbortController(), captureEpoch: 0 };
+ this.resources.set(requestId, resources);
+ this.patch({ starting: true, errorCode: undefined, transcripts: [] });
+
+ let prepareRequest: ReturnType<typeof liveVoiceApi.prepare> | undefined;
+ let micRequest: Promise<MediaStream> | undefined;
+ try {
+ // Browser activation is transient: begin permission and AudioContext work
+ // synchronously in the click handler. Main reserves the microphone lease
+ // as soon as it accepts prepare, before this renderer permission prompt.
+ prepareRequest = liveVoiceApi.prepare({
+ requestId,
+ bindingId: selected.bindingId,
+ expectedSettingsRevision: cachedStatus.settingsRevision,
+ initialMuted: true,
+ });
+ void prepareRequest.then((prepared) => {
+ if (resources.abort.signal.aborted || generation !== this.generation) {
+ void liveVoiceApi.end({ callId: prepared.callId, reason: "user-cancelled-start" }).catch(() => undefined);
+ }
+ }).catch(() => undefined);
+ micRequest = requestMicrophone(this.microphoneDeviceId);
+ void micRequest.then((stream) => {
+ if (resources.abort.signal.aborted || generation !== this.generation) stopStream(stream);
+ }).catch(() => undefined);
+ if (selected.adapterId !== "codex-live") {
+ resources.context = new AudioContext({ sampleRate: 48_000 });
+ void resources.context.resume().catch(() => undefined);
+ }
+ if (!prepareRequest || !micRequest) throw liveError("LIVE_MEDIA_UNSUPPORTED");
+ const [stream, freshStatus, prepared] = await Promise.all([
+ abortableMicrophone(micRequest, resources.abort.signal),
+ liveVoiceApi.status(),
+ prepareRequest,
+ ]);
+ resources.callId = prepared.callId;
+ this.resources.set(prepared.callId, resources);
+ if (generation !== this.generation) throw liveError("LIVE_STALE_CALL");
+ const freshBinding = freshStatus.bindings.find((item) => item.bindingId === selected.bindingId && item.selectable);
+ if (!freshStatus.enabled || freshStatus.settingsRevision !== cachedStatus.settingsRevision || freshStatus.selectedBindingId !== cachedStatus.selectedBindingId || !freshBinding) {
+ await liveVoiceApi.end({ callId: prepared.callId, reason: "user-cancelled-start" }).catch(() => undefined);
+ throw liveError("LIVE_SETTINGS_IN_USE");
+ }
+ this.patch({ status: freshStatus });
+ if (generation !== this.generation || resources.abort.signal.aborted) throw liveError("LIVE_STALE_CALL");
+ resources.stream = stream;
+ if (resources.stream.getAudioTracks().length !== 1) throw liveError("LIVE_MEDIA_UNSUPPORTED");
+ await liveVoiceApi.reportMedia({ callId: prepared.callId, kind: "microphone-active", active: true });
+ this.patchCallIfNewer({ callId: prepared.callId, revision: prepared.revision, bindingId: prepared.bindingId, adapterId: prepared.adapterId, phase: "acquiring-mic", muted: true, microphoneActive: true, userSpeaking: false, assistantSpeaking: false, mediaRelease: "pending" });
+
+ if (prepared.mediaKind === "pcm") {
+ if (!prepared.portNonce) throw liveError("LIVE_PROTOCOL_ERROR");
+ const port = await this.waitForPort(prepared.callId, prepared.portNonce, resources.abort.signal);
+ resources.port = port;
+ const context = resources.context;
+ if (!context) throw liveError("LIVE_MEDIA_UNSUPPORTED");
+ resources.pcm = await LivePcmSession.create({
+ callId: prepared.callId,
+ portNonce: prepared.portNonce,
+ port,
+ stream: resources.stream,
+ inputSampleRate: prepared.inputSampleRate,
+ workletUrl: pcmWorkletUrl,
+ context,
+ onFailure: (error) => void this.failActive(prepared.callId, error),
+ onPlayback: (cursors) => void liveVoiceApi.reportPlayback({ callId: prepared.callId, cursors }).catch((error) => this.failActive(prepared.callId, error)),
+ });
+ await resources.pcm.start(Promise.resolve(), resources.abort.signal);
+ await liveVoiceApi.reportMedia({ callId: prepared.callId, kind: "phase", phase: "connecting" });
+ await liveVoiceApi.connect({ callId: prepared.callId });
+ } else {
+ await this.connectWebRtc(prepared.callId, resources);
+ }
+ if (generation !== this.generation || resources.abort.signal.aborted) throw liveError("LIVE_STALE_CALL");
+ await liveVoiceApi.reportMedia({ callId: prepared.callId, kind: "phase", phase: "connected" });
+ this.patch({ starting: false });
+ resources.heartbeat = setInterval(() => {
+ void liveVoiceApi.heartbeat(prepared.callId).catch((error) => this.failActive(prepared.callId, error));
+ }, 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);
+ }
+ 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) });
+ throw error;
+ } finally {
+ if (this.snapshot.starting && generation === this.generation && !resources.callId) this.patch({ starting: false });
+ }
+ }
+
+ async cancelStart(): Promise<void> {
+ const resource = this.snapshot.starting ? [...this.resources.values()].at(-1) : undefined;
+ 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);
+ await this.releaseResources(resource, Boolean(resource.callId));
+ this.resources.delete(resource.requestId);
+ this.patch({ starting: false });
+ }
+
+ async toggleMute(): Promise<void> {
+ const call = this.snapshot.call;
+ if (!call || call.phase !== "connected") return;
+ const resources = this.resources.get(call.callId);
+ if (!resources) return;
+ const muted = !call.muted;
+ const captureEpoch = resources.captureEpoch + 1;
+ resources.captureEpoch = captureEpoch;
+ try {
+ if (resources.pcm) resources.pcm.applyGate(muted, captureEpoch);
+ else for (const track of resources.stream?.getAudioTracks() ?? []) track.enabled = !muted;
+ const updated = await liveVoiceApi.setMuted({ callId: call.callId, muted, captureEpoch });
+ this.patch({ call: updated });
+ } catch (error) {
+ for (const track of resources.stream?.getAudioTracks() ?? []) track.enabled = false;
+ resources.pcm?.applyGate(true, captureEpoch + 1);
+ this.patch({ call: { ...call, muted: true }, errorCode: errorCode(error) });
+ await this.failActive(call.callId, error);
+ }
+ }
+
+ async resumePlayback(): Promise<void> {
+ const call = this.snapshot.call;
+ if (!call) return;
+ const resources = this.resources.get(call.callId);
+ if (!resources) return;
+ try {
+ await resources.pcm?.resumePlayback();
+ await resources.audio?.play();
+ await liveVoiceApi.reportMedia({ callId: call.callId, kind: "playback-blocked", blocked: false });
+ } catch (error) {
+ this.patch({ errorCode: errorCode(error) });
+ }
+ }
+
+ 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) }));
+ }
+
+ private async connectWebRtc(callId: string, resources: StartResources): Promise<void> {
+ const stream = resources.stream;
+ if (!stream) throw liveError("LIVE_MEDIA_UNSUPPORTED");
+ const peer = new RTCPeerConnection({ iceServers: [] });
+ resources.peer = peer;
+ const channel = peer.createDataChannel("oai-events");
+ resources.channel = channel;
+ channel.onmessage = (event) => this.handleCodexData(callId, resources, event.data);
+ channel.onerror = () => void this.failActive(callId, liveError("LIVE_NETWORK_ERROR"));
+ channel.onclose = () => {
+ if (!resources.abort.signal.aborted) void this.failActive(callId, liveError("LIVE_NETWORK_ERROR"));
+ };
+ peer.onconnectionstatechange = () => {
+ if (peer.connectionState === "failed" && !resources.abort.signal.aborted) void this.failActive(callId, liveError("LIVE_NETWORK_ERROR"));
+ };
+ for (const track of stream.getAudioTracks()) {
+ track.enabled = false;
+ peer.addTrack(track, stream);
+ }
+ peer.ontrack = (event) => {
+ const audio = document.createElement("audio");
+ audio.autoplay = true;
+ audio.setAttribute("playsinline", "");
+ audio.setAttribute("aria-hidden", "true");
+ audio.style.position = "fixed";
+ audio.style.width = "1px";
+ audio.style.height = "1px";
+ audio.style.opacity = "0";
+ audio.srcObject = event.streams[0] ?? new MediaStream([event.track]);
+ document.body.append(audio);
+ resources.audio?.remove();
+ resources.audio = audio;
+ void audio.play().then(
+ () => liveVoiceApi.reportMedia({ callId, kind: "playback-blocked", blocked: false }).catch(() => undefined),
+ () => liveVoiceApi.reportMedia({ callId, kind: "playback-blocked", blocked: true }).catch(() => undefined),
+ );
+ };
+ const offer = await peer.createOffer();
+ await peer.setLocalDescription(offer);
+ await waitForIceGathering(peer, resources.abort.signal);
+ const offerSdp = peer.localDescription?.sdp;
+ if (!offerSdp) throw liveError("LIVE_PROTOCOL_ERROR");
+ await liveVoiceApi.reportMedia({ callId, kind: "phase", phase: "connecting" });
+ const result = await liveVoiceApi.connect({ callId, offerSdp });
+ if (!result.answerSdp) throw liveError("LIVE_PROTOCOL_ERROR");
+ await peer.setRemoteDescription({ type: "answer", sdp: result.answerSdp });
+ await Promise.all([
+ waitForPeerConnection(peer, resources.abort.signal),
+ waitForDataChannel(channel, resources.abort.signal),
+ ]);
+ }
+
+ private handleCodexData(callId: string, resources: StartResources, raw: unknown): void {
+ if (typeof raw !== "string" || raw.length > 2 * 1024 * 1024) {
+ void this.failActive(callId, liveError("LIVE_PROTOCOL_ERROR"));
+ return;
+ }
+ try {
+ const value: unknown = JSON.parse(raw);
+ for (const event of parseCodexMessage(value)) {
+ switch (event.kind) {
+ case "delegation":
+ void liveVoiceApi.reportDelegation({ callId, delegationId: event.delegationId, instruction: event.instruction }).catch((error) => this.failActive(callId, error));
+ break;
+ case "transcript":
+ this.handleTranscript(callId, { id: event.id, role: event.role, text: event.text, final: event.final, timestamp: Date.now() });
+ break;
+ case "activity":
+ void liveVoiceApi.reportMedia({ callId, kind: "activity", userSpeaking: event.userSpeaking, assistantSpeaking: event.assistantSpeaking }).catch((error) => this.failActive(callId, error));
+ break;
+ case "error":
+ void this.failActive(callId, liveError(event.code));
+ break;
+ default:
+ break;
+ }
+ }
+ } catch (error) {
+ void this.failActive(callId, liveError("LIVE_PROTOCOL_ERROR", String(error)));
+ }
+ }
+
+ private readonly handlePortMessage = (event: MessageEvent): void => {
+ if (event.source !== window || event.origin !== window.location.origin || !event.data || typeof event.data !== "object") return;
+ const data = event.data as { kind?: unknown; callId?: unknown; nonce?: unknown };
+ const port = event.ports[0];
+ if (data.kind !== "pi-desktop-live-voice-port" || typeof data.callId !== "string" || typeof data.nonce !== "string" || !/^[0-9a-f-]{36}$/i.test(data.nonce) || !port || event.ports.length !== 1) return;
+ const waiter = this.portWaiters.get(data.callId);
+ if (waiter) {
+ clearTimeout(waiter.timer);
+ this.portWaiters.delete(data.callId);
+ if (waiter.nonce === data.nonce) waiter.resolve(port);
+ else {
+ port.close();
+ waiter.reject(liveError("LIVE_INVALID_OWNER"));
+ }
+ return;
+ }
+ for (const [priorId, priorPort] of this.pendingPorts) {
+ priorPort.port.close();
+ this.pendingPorts.delete(priorId);
+ }
+ this.pendingPorts.set(data.callId, { port, nonce: data.nonce });
+ };
+
+ private waitForPort(callId: string, nonce: string, signal: AbortSignal): Promise<MessagePort> {
+ const pending = this.pendingPorts.get(callId);
+ if (pending) {
+ this.pendingPorts.delete(callId);
+ if (pending.nonce === nonce) return Promise.resolve(pending.port);
+ pending.port.close();
+ return Promise.reject(liveError("LIVE_INVALID_OWNER"));
+ }
+ return new Promise<MessagePort>((resolve, reject) => {
+ const timer = setTimeout(() => {
+ this.portWaiters.delete(callId);
+ signal.removeEventListener("abort", onAbort);
+ reject(liveError("LIVE_TIMEOUT"));
+ }, 3_000);
+ const onAbort = () => {
+ clearTimeout(timer);
+ this.portWaiters.delete(callId);
+ reject(liveError("LIVE_STALE_CALL"));
+ };
+ this.portWaiters.set(callId, {
+ nonce,
+ resolve: (port) => {
+ signal.removeEventListener("abort", onAbort);
+ resolve(port);
+ },
+ reject,
+ timer,
+ });
+ signal.addEventListener("abort", onAbort, { once: true });
+ if (signal.aborted) onAbort();
+ });
+ }
+
+ private handleView(view: LiveCallView): void {
+ 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"
+ ? [...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") {
+ this.terminalCallIds.add(view.callId);
+ while (this.terminalCallIds.size > 16) this.terminalCallIds.delete(this.terminalCallIds.values().next().value as string);
+ }
+ }
+
+ private handleControl(event: LiveControlEvent): void {
+ const resources = this.resources.get(event.callId);
+ if (!resources) return;
+ if (event.kind === "release-media") {
+ void this.releaseResources(resources, true);
+ return;
+ }
+ if (event.kind === "playback-reset") {
+ resources.pcm?.resetPlayback(event.playbackEpoch);
+ return;
+ }
+ const channel = resources.channel;
+ try {
+ if (!channel || channel.readyState !== "open") throw liveError("LIVE_NETWORK_ERROR");
+ channel.send(codexDelegationFeedback(event.delegationId));
+ void liveVoiceApi.reportControlApplied({ callId: event.callId, actionId: event.actionId, applied: true });
+ } catch (error) {
+ void liveVoiceApi.reportControlApplied({ callId: event.callId, actionId: event.actionId, applied: false, errorCode: errorCode(error) });
+ }
+ }
+
+ private handleTranscript(callId: string, segment: LiveTranscriptSegment): void {
+ const call = this.snapshot.call;
+ if (!call || call.callId !== callId) return;
+ const current = this.snapshot.transcripts;
+ const index = current.findIndex((item) => item.id === segment.id && item.role === segment.role);
+ const next = index >= 0
+ ? current.map((item, itemIndex) => itemIndex === index ? segment : item)
+ : [...current, segment].slice(-MAX_TRANSCRIPTS);
+ this.patch({ transcripts: next });
+ }
+
+ private async failActive(callId: string, error: unknown): Promise<void> {
+ const resources = this.resources.get(callId);
+ if (!resources) return;
+ this.patch({ errorCode: errorCode(error) });
+ 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 async releaseResourcesOnce(resources: StartResources, notifyMain: boolean): Promise<void> {
+ if (resources.heartbeat) clearInterval(resources.heartbeat);
+ resources.abort.abort();
+ resources.stream && stopStream(resources.stream);
+ resources.channel?.close();
+ resources.peer?.close();
+ if (resources.audio) {
+ resources.audio.pause();
+ resources.audio.srcObject = null;
+ resources.audio.remove();
+ }
+ 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) resources.port.close();
+ }
+
+ private readonly handlePageHide = (): void => {
+ const call = this.snapshot.call;
+ if (call) void liveVoiceApi.end({ callId: call.callId, reason: "renderer-gone" }).catch(() => undefined);
+ else void this.cancelStart();
+ for (const dispose of this.disposers) dispose();
+ };
+
+ private patch(patch: Partial<LiveVoiceSnapshot>): void {
+ this.snapshot = { ...this.snapshot, ...patch };
+ for (const listener of this.listeners) listener();
+ }
+
+ private patchCallIfNewer(call: LiveCallView): void {
+ const current = this.snapshot.call;
+ if (current?.callId === call.callId && current.revision > call.revision) return;
+ this.patch({ call });
+ }
+}
+
+let controller: LiveCallController | null = null;
+
+export function getLiveCallController(): LiveCallController {
+ controller ??= new LiveCallController();
+ return controller;
+}
+
+function requestMicrophone(deviceId: string | null): Promise<MediaStream> {
+ if (!navigator.mediaDevices?.getUserMedia) return Promise.reject(liveError("LIVE_MEDIA_UNSUPPORTED"));
+ return navigator.mediaDevices.getUserMedia({
+ audio: {
+ ...(deviceId ? { deviceId: { exact: deviceId } } : {}),
+ channelCount: 1,
+ echoCancellation: true,
+ noiseSuppression: true,
+ autoGainControl: true,
+ },
+ video: false,
+ });
+}
+
+function abortableMicrophone(promise: Promise<MediaStream>, signal: AbortSignal): Promise<MediaStream> {
+ return new Promise<MediaStream>((resolve, reject) => {
+ const onAbort = () => reject(liveError("LIVE_STALE_CALL"));
+ signal.addEventListener("abort", onAbort, { once: true });
+ promise.then((stream) => {
+ signal.removeEventListener("abort", onAbort);
+ if (signal.aborted) {
+ stopStream(stream);
+ reject(liveError("LIVE_STALE_CALL"));
+ } else resolve(stream);
+ }, (error: unknown) => {
+ signal.removeEventListener("abort", onAbort);
+ reject(error);
+ });
+ if (signal.aborted) onAbort();
+ });
+}
+
+function stopStream(stream: MediaStream): void {
+ for (const track of stream.getTracks()) track.stop();
+}
+
+function isLive(phase?: LiveCallView["phase"]): boolean {
+ return phase !== undefined && !["idle", "ended", "failed"].includes(phase);
+}
+
+function errorCode(error: unknown): string {
+ if (error && typeof error === "object" && "name" in error && error.name === "NotAllowedError") return "LIVE_MICROPHONE_DENIED";
+ if (error && typeof error === "object" && "name" in error && ["NotFoundError", "NotReadableError", "OverconstrainedError"].includes(String(error.name))) {
+ return "LIVE_MICROPHONE_UNAVAILABLE";
+ }
+ return error && typeof error === "object" && "code" in error && typeof error.code === "string"
+ ? error.code
+ : error && typeof error === "object" && "errorCode" in error && typeof error.errorCode === "string"
+ ? error.errorCode
+ : "LIVE_NETWORK_ERROR";
+}
+
+async function waitForIceGathering(peer: RTCPeerConnection, signal: AbortSignal): Promise<void> {
+ if (peer.iceGatheringState === "complete") return;
+ await waitEvent(peer, "icegatheringstatechange", () => peer.iceGatheringState === "complete", signal, ICE_GATHER_TIMEOUT_MS);
+}
+
+async function waitForPeerConnection(peer: RTCPeerConnection, signal: AbortSignal): Promise<void> {
+ if (peer.connectionState === "connected") return;
+ if (signal.aborted) throw liveError("LIVE_STALE_CALL");
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => finish(liveError("LIVE_TIMEOUT")), 15_000);
+ const onChange = () => {
+ if (peer.connectionState === "connected") finish();
+ else if (peer.connectionState === "failed" || peer.connectionState === "closed") finish(liveError("LIVE_NETWORK_ERROR"));
+ };
+ const onAbort = () => finish(liveError("LIVE_STALE_CALL"));
+ const finish = (error?: Error) => {
+ clearTimeout(timer);
+ peer.removeEventListener("connectionstatechange", onChange);
+ signal.removeEventListener("abort", onAbort);
+ error ? reject(error) : resolve();
+ };
+ peer.addEventListener("connectionstatechange", onChange);
+ signal.addEventListener("abort", onAbort, { once: true });
+ onChange();
+ });
+}
+
+async function waitForDataChannel(channel: RTCDataChannel, signal: AbortSignal): Promise<void> {
+ if (channel.readyState === "open") return;
+ if (signal.aborted) throw liveError("LIVE_STALE_CALL");
+ await new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => finish(liveError("LIVE_TIMEOUT")), 15_000);
+ const onOpen = () => finish();
+ const onError = () => finish(liveError("LIVE_NETWORK_ERROR"));
+ const onClose = () => finish(liveError("LIVE_NETWORK_ERROR"));
+ const onAbort = () => finish(liveError("LIVE_STALE_CALL"));
+ const finish = (error?: Error) => {
+ clearTimeout(timer);
+ channel.removeEventListener("open", onOpen);
+ channel.removeEventListener("error", onError);
+ channel.removeEventListener("close", onClose);
+ signal.removeEventListener("abort", onAbort);
+ error ? reject(error) : resolve();
+ };
+ channel.addEventListener("open", onOpen, { once: true });
+ channel.addEventListener("error", onError, { once: true });
+ channel.addEventListener("close", onClose, { once: true });
+ signal.addEventListener("abort", onAbort, { once: true });
+ if (channel.readyState === "open") finish();
+ });
+}
+
+function waitEvent<T extends EventTarget>(target: T, name: string, predicate: () => boolean, signal: AbortSignal, timeoutMs: number): Promise<void> {
+ return new Promise<void>((resolve, reject) => {
+ const timer = setTimeout(() => finish(liveError("LIVE_TIMEOUT")), timeoutMs);
+ const onEvent = () => { if (predicate()) finish(); };
+ const onAbort = () => finish(liveError("LIVE_STALE_CALL"));
+ const finish = (error?: Error) => {
+ clearTimeout(timer);
+ target.removeEventListener(name, onEvent);
+ signal.removeEventListener("abort", onAbort);
+ error ? reject(error) : resolve();
+ };
+ target.addEventListener(name, onEvent);
+ signal.addEventListener("abort", onAbort, { once: true });
+ onEvent();
+ });
+}
diff --git a/apps/desktop/src/features/voice/live/live-pcm-session.ts b/apps/desktop/src/features/voice/live/live-pcm-session.ts
new file mode 100644
index 000000000..25cb68ee4
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/live-pcm-session.ts
@@ -0,0 +1,295 @@
+import { decodePcm16, encodePcm16, StreamingPcmResampler } from "@pi-desktop/voice-runtime/live";
+import type { LivePlaybackCursor } from "@pi-desktop/shared";
+import { liveError } from "./live-voice-api";
+
+const MAX_INPUT_CREDITS = 10;
+const MAX_PCM_FRAME_SAMPLES = 2400;
+const MAX_WORKLET_MESSAGE_SAMPLES = 48_000;
+
+export class LivePcmSession {
+ private readonly callId: string;
+ private readonly portNonce: string;
+ private readonly port: MessagePort;
+ private readonly inputSampleRate: 16000 | 24000;
+ private readonly onFailure: (error: unknown) => void;
+ private readonly onPlayback: (cursors: LivePlaybackCursor[]) => void;
+ private readonly context: AudioContext;
+ private readonly source: MediaStreamAudioSourceNode;
+ private readonly node: AudioWorkletNode;
+ private readonly resampler: StreamingPcmResampler;
+ private inputCredits = 0;
+ private portReady = false;
+ private nextInputSequence = 1;
+ private captureEpoch = 0;
+ private muted = true;
+ private readyResolve: (() => void) | null = null;
+ private readyReject: ((error: Error) => void) | null = null;
+ private releasePromise: Promise<void> | null = null;
+ private releaseSent = false;
+ private disposed = false;
+
+ static async create(input: {
+ callId: string;
+ portNonce: string;
+ port: MessagePort;
+ stream: MediaStream;
+ inputSampleRate: 16000 | 24000;
+ workletUrl: string;
+ context: AudioContext;
+ onFailure: (error: unknown) => void;
+ onPlayback: (cursors: LivePlaybackCursor[]) => void;
+ }): Promise<LivePcmSession> {
+ const context = input.context;
+ if (!context.audioWorklet) {
+ await context.close().catch(() => undefined);
+ throw liveError("LIVE_MEDIA_UNSUPPORTED", "AudioWorklet is unavailable");
+ }
+ try {
+ await context.audioWorklet.addModule(input.workletUrl);
+ return new LivePcmSession(input);
+ } catch (error) {
+ await context.close().catch(() => undefined);
+ throw error;
+ }
+ }
+
+ private constructor(input: {
+ callId: string;
+ portNonce: string;
+ port: MessagePort;
+ stream: MediaStream;
+ inputSampleRate: 16000 | 24000;
+ workletUrl: string;
+ onFailure: (error: unknown) => void;
+ onPlayback: (cursors: LivePlaybackCursor[]) => void;
+ context: AudioContext;
+ }) {
+ this.callId = input.callId;
+ this.portNonce = input.portNonce;
+ this.port = input.port;
+ this.inputSampleRate = input.inputSampleRate;
+ this.onFailure = input.onFailure;
+ this.onPlayback = input.onPlayback;
+ this.context = input.context;
+ this.resampler = new StreamingPcmResampler(this.context.sampleRate, this.inputSampleRate);
+ this.source = this.context.createMediaStreamSource(input.stream);
+ this.node = new AudioWorkletNode(this.context, "pi-live-pcm", {
+ numberOfInputs: 1,
+ numberOfOutputs: 1,
+ outputChannelCount: [1],
+ channelCount: 1,
+ channelCountMode: "explicit",
+ });
+ this.source.connect(this.node);
+ this.node.connect(this.context.destination);
+ this.node.port.onmessage = (event: MessageEvent<unknown>) => this.handleWorkletMessage(event.data);
+ this.port.onmessage = (event: MessageEvent<unknown>) => this.handleMainMessage(event.data);
+ this.port.onmessageerror = () => this.onFailure(liveError("LIVE_PROTOCOL_ERROR"));
+ this.port.start();
+ this.port.postMessage({ kind: "hello", callId: this.callId, nonce: input.portNonce });
+ }
+
+ async start(workletReady: Promise<void>, signal: AbortSignal): Promise<void> {
+ await workletReady;
+ if (signal.aborted) throw liveError("LIVE_STALE_CALL");
+ try {
+ await this.context.resume();
+ } catch (error) {
+ throw Object.assign(liveError("LIVE_PLAYBACK_BLOCKED", "Audio playback could not be started"), { cause: error });
+ }
+ await this.waitForReady(signal);
+ }
+
+ applyGate(muted: boolean, captureEpoch: number): void {
+ if (this.disposed || !Number.isSafeInteger(captureEpoch) || captureEpoch < this.captureEpoch) return;
+ this.muted = muted;
+ this.captureEpoch = captureEpoch;
+ this.node.port.postMessage({ kind: "set-gate", muted, captureEpoch });
+ }
+
+ async resumePlayback(): Promise<void> {
+ if (this.disposed) throw liveError("LIVE_STALE_CALL");
+ try {
+ await this.context.resume();
+ } catch (error) {
+ throw Object.assign(liveError("LIVE_PLAYBACK_BLOCKED", "Audio playback could not be resumed"), { cause: error });
+ }
+ }
+
+ resetPlayback(playbackEpoch: number): void {
+ if (this.disposed || !Number.isSafeInteger(playbackEpoch)) return;
+ this.node.port.postMessage({ kind: "playback-reset", playbackEpoch });
+ }
+
+ async release(): Promise<void> {
+ if (this.releasePromise) return this.releasePromise;
+ this.releasePromise = (async () => {
+ if (this.disposed) return;
+ this.disposed = true;
+ this.resampler.reset();
+ this.source.disconnect();
+ this.node.port.postMessage({ kind: "release" });
+ this.node.disconnect();
+ try {
+ if (this.context.state !== "closed") await this.context.close();
+ } catch {
+ // The microphone track is stopped by the owning call controller before this closes the context.
+ } finally {
+ if (!this.releaseSent) {
+ this.releaseSent = true;
+ this.port.postMessage({ kind: "released", callId: this.callId });
+ }
+ }
+ })();
+ return this.releasePromise;
+ }
+
+ private waitForReady(signal: AbortSignal): Promise<void> {
+ if (this.portReady) return Promise.resolve();
+ return new Promise<void>((resolve, reject) => {
+ let finished = false;
+ let timer: ReturnType<typeof setTimeout>;
+ const cleanup = () => {
+ if (finished) return;
+ finished = true;
+ clearTimeout(timer);
+ signal.removeEventListener("abort", onAbort);
+ this.readyResolve = null;
+ this.readyReject = null;
+ };
+ const onAbort = () => {
+ cleanup();
+ reject(liveError("LIVE_STALE_CALL"));
+ };
+ timer = setTimeout(() => {
+ cleanup();
+ reject(liveError("LIVE_TIMEOUT", "Live audio port did not become ready", true));
+ }, 3_000);
+ this.readyResolve = () => {
+ cleanup();
+ resolve();
+ };
+ this.readyReject = (error) => {
+ cleanup();
+ reject(error);
+ };
+ signal.addEventListener("abort", onAbort, { once: true });
+ if (signal.aborted) onAbort();
+ });
+ }
+
+ private handleMainMessage(value: unknown): void {
+ const message = asRecord(value);
+ if (!message || message.callId !== this.callId || typeof message.kind !== "string") {
+ this.onFailure(liveError("LIVE_PROTOCOL_ERROR"));
+ return;
+ }
+ switch (message.kind) {
+ case "ready":
+ if (message.nonce !== this.portNonce || !Number.isSafeInteger(message.inputCredits) || (message.inputCredits as number) < 0 || (message.inputCredits as number) > MAX_INPUT_CREDITS || message.outputSampleRate !== 24000) {
+ this.onFailure(liveError("LIVE_PROTOCOL_ERROR"));
+ return;
+ }
+ this.inputCredits = message.inputCredits as number;
+ this.portReady = true;
+ this.readyResolve?.();
+ return;
+ case "credit":
+ if (message.direction === "uplink" && Number.isSafeInteger(message.consumedSequence)) {
+ this.inputCredits = Math.min(MAX_INPUT_CREDITS, this.inputCredits + 1);
+ }
+ return;
+ case "set-gate":
+ if (typeof message.muted !== "boolean" || !Number.isSafeInteger(message.captureEpoch)) return;
+ this.applyGate(message.muted, message.captureEpoch as number);
+ return;
+ case "output-pcm": {
+ if (!(message.pcm16 instanceof ArrayBuffer) || message.pcm16.byteLength === 0 || message.pcm16.byteLength > MAX_PCM_FRAME_SAMPLES * 2 || message.pcm16.byteLength % 2 !== 0) {
+ this.onFailure(liveError("LIVE_PROTOCOL_ERROR"));
+ return;
+ }
+ const samples = decodePcm16(new Uint8Array(message.pcm16));
+ const buffer = samples.buffer.slice(samples.byteOffset, samples.byteOffset + samples.byteLength) as ArrayBuffer;
+ this.node.port.postMessage({
+ kind: "output-pcm",
+ sequence: message.sequence,
+ playbackEpoch: message.playbackEpoch,
+ responseKey: message.responseKey,
+ itemId: message.itemId,
+ contentIndex: message.contentIndex,
+ sampleOffset: message.sampleOffset,
+ samples: buffer,
+ }, [buffer]);
+ return;
+ }
+ case "interrupt":
+ if (typeof message.requestId !== "string" || !Number.isSafeInteger(message.playbackEpoch)) return;
+ this.node.port.postMessage({ kind: "interrupt", requestId: message.requestId, playbackEpoch: message.playbackEpoch });
+ return;
+ case "playback-reset":
+ if (Number.isSafeInteger(message.playbackEpoch)) this.node.port.postMessage({ kind: "playback-reset", playbackEpoch: message.playbackEpoch });
+ return;
+ case "release":
+ void this.release().catch(this.onFailure);
+ return;
+ default:
+ this.onFailure(liveError("LIVE_PROTOCOL_ERROR"));
+ }
+ }
+
+ private handleWorkletMessage(value: unknown): void {
+ const message = asRecord(value);
+ if (!message || typeof message.kind !== "string") return this.onFailure(liveError("LIVE_PROTOCOL_ERROR"));
+ switch (message.kind) {
+ case "input-frame":
+ if (!(message.samples instanceof ArrayBuffer) || !Number.isSafeInteger(message.sampleRate) || message.sampleRate !== this.context.sampleRate || !Number.isSafeInteger(message.captureEpoch)) {
+ this.onFailure(liveError("LIVE_PROTOCOL_ERROR"));
+ return;
+ }
+ this.sendInput(new Float32Array(message.samples), message.captureEpoch as number);
+ return;
+ case "gate-applied":
+ if (typeof message.muted !== "boolean" || !Number.isSafeInteger(message.captureEpoch)) return;
+ this.port.postMessage({ kind: "gate-applied", callId: this.callId, muted: message.muted, captureEpoch: message.captureEpoch });
+ return;
+ case "playback-position":
+ if (!Array.isArray(message.cursors)) return;
+ this.onPlayback(message.cursors as LivePlaybackCursor[]);
+ this.port.postMessage({ kind: "playback-position", callId: this.callId, cursors: message.cursors });
+ return;
+ case "chunk-played":
+ case "chunk-dropped":
+ if (Number.isSafeInteger(message.sequence)) this.port.postMessage({ kind: "credit", callId: this.callId, direction: "downlink", consumedSequence: message.sequence });
+ return;
+ case "interruption-applied":
+ if (typeof message.requestId !== "string" || !Array.isArray(message.cursors) || !Number.isSafeInteger(message.playbackEpoch)) return;
+ this.onPlayback(message.cursors as LivePlaybackCursor[]);
+ this.port.postMessage({ kind: "interruption-applied", callId: this.callId, requestId: message.requestId, playbackEpoch: message.playbackEpoch, cursors: message.cursors });
+ return;
+ case "media-stopped":
+ return;
+ default:
+ this.onFailure(liveError("LIVE_PROTOCOL_ERROR"));
+ }
+ }
+
+ private sendInput(samples: Float32Array, captureEpoch: number): void {
+ if (this.disposed || this.muted || captureEpoch !== this.captureEpoch || this.inputCredits <= 0) return;
+ const converted = this.resampler.push(samples);
+ for (let offset = 0; offset < converted.length; offset += MAX_PCM_FRAME_SAMPLES) {
+ const chunk = converted.subarray(offset, Math.min(converted.length, offset + MAX_PCM_FRAME_SAMPLES));
+ if (chunk.length === 0 || this.inputCredits <= 0) return;
+ const pcm16 = encodePcm16(chunk);
+ const buffer = pcm16.buffer.slice(pcm16.byteOffset, pcm16.byteOffset + pcm16.byteLength) as ArrayBuffer;
+ const sequence = this.nextInputSequence++;
+ this.inputCredits -= 1;
+ this.port.postMessage({ kind: "input-pcm", callId: this.callId, sequence, captureEpoch, pcm16: buffer }, [buffer]);
+ }
+ }
+}
+
+function asRecord(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null;
+}
diff --git a/apps/desktop/src/features/voice/live/live-voice-api.ts b/apps/desktop/src/features/voice/live/live-voice-api.ts
new file mode 100644
index 000000000..88966081a
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/live-voice-api.ts
@@ -0,0 +1,51 @@
+import {
+ IPC,
+ type LiveConnectRequest,
+ type LiveConnectResult,
+ type LiveControlEvent,
+ type LiveDelegationRequest,
+ type LiveEndRequest,
+ type LiveMediaReport,
+ type LivePlaybackCursor,
+ type LivePrepareRequest,
+ type LivePreparedCall,
+ type LiveStatus,
+ type LiveTranscriptEvent,
+} from "@pi-desktop/shared";
+import type { LiveCallView } from "@pi-desktop/shared";
+
+async function invoke<T>(channel: string, ...args: unknown[]): Promise<T> {
+ const bridge = window.piDesktop;
+ if (!bridge) throw liveError("LIVE_INVALID_OWNER", "Live Voice bridge unavailable");
+ const result = await bridge.invoke<T>(channel, ...args);
+ if (!result.ok) {
+ throw liveError(result.error.code, result.error.message, result.error.retriable === true);
+ }
+ return result.data;
+}
+
+export const liveVoiceApi = {
+ status: () => invoke<LiveStatus>(IPC.invoke.liveVoiceStatus),
+ prepare: (request: LivePrepareRequest) => invoke<LivePreparedCall>(IPC.invoke.liveVoicePrepare, request),
+ connect: (request: LiveConnectRequest) => invoke<LiveConnectResult>(IPC.invoke.liveVoiceConnect, request),
+ setMuted: (request: { callId: string; muted: boolean; captureEpoch: number }) => invoke<LiveCallView>(IPC.invoke.liveVoiceSetMuted, request),
+ reportMedia: (report: LiveMediaReport) => invoke<LiveCallView>(IPC.invoke.liveVoiceReportMedia, report),
+ reportPlayback: (input: { callId: string; cursors: LivePlaybackCursor[] }) => invoke<{ ok: true }>(IPC.invoke.liveVoiceReportPlayback, input),
+ reportDelegation: (request: LiveDelegationRequest) => invoke<{ accepted: boolean }>(IPC.invoke.liveVoiceReportDelegation, request),
+ reportControlApplied: (input: { callId: string; actionId: string; applied: boolean; errorCode?: string }) => invoke<{ ok: true }>(IPC.invoke.liveVoiceReportControlApplied, input),
+ end: (request: LiveEndRequest) => invoke<{ ok: true }>(IPC.invoke.liveVoiceEnd, request),
+ heartbeat: (callId: string) => invoke<{ ok: true }>(IPC.invoke.liveVoiceHeartbeat, { callId }),
+ onView: (listener: (view: LiveCallView) => void) => subscribe(IPC.event.liveVoiceChanged, listener),
+ onControl: (listener: (event: LiveControlEvent) => void) => subscribe(IPC.event.liveVoiceControl, listener),
+ onTranscript: (listener: (event: LiveTranscriptEvent) => void) => subscribe(IPC.event.liveVoiceTranscript, listener),
+};
+
+function subscribe<T>(channel: string, listener: (value: T) => void): () => void {
+ const bridge = window.piDesktop;
+ if (!bridge) return () => undefined;
+ return bridge.on(channel, (value) => listener(value as T));
+}
+
+export function liveError(code: string, message = code, retriable = false): Error & { code: string; retriable: boolean } {
+ return Object.assign(new Error(message), { code, retriable });
+}
diff --git a/apps/desktop/src/features/voice/live/pcm-worklet.js b/apps/desktop/src/features/voice/live/pcm-worklet.js
new file mode 100644
index 000000000..7286934d6
--- /dev/null
+++ b/apps/desktop/src/features/voice/live/pcm-worklet.js
@@ -0,0 +1,163 @@
+const PLAYBACK_SAMPLE_RATE = 24000;
+const CAPTURE_FRAME_MS = 20;
+
+class PiLivePcmProcessor extends AudioWorkletProcessor {
+ constructor() {
+ super();
+ this.captureMuted = true;
+ this.captureEpoch = 0;
+ this.captureFrameSize = Math.max(1, Math.round(sampleRate * CAPTURE_FRAME_MS / 1000));
+ this.captureFrame = new Float32Array(this.captureFrameSize);
+ this.captureOffset = 0;
+ this.playbackEpoch = 0;
+ this.playbackQueue = [];
+ this.currentChunk = null;
+ this.playbackCursors = new Map();
+ this.renderedSinceReport = 0;
+ this.stopped = false;
+ this.port.onmessage = (event) => this.handleMessage(event.data);
+ }
+
+ handleMessage(message) {
+ if (!message || typeof message !== "object") return;
+ if (message.kind === "set-gate") {
+ if (!Number.isSafeInteger(message.captureEpoch) || message.captureEpoch < this.captureEpoch || typeof message.muted !== "boolean") return;
+ this.captureEpoch = message.captureEpoch;
+ this.captureMuted = message.muted;
+ this.captureOffset = 0;
+ this.port.postMessage({ kind: "gate-applied", captureEpoch: this.captureEpoch, muted: this.captureMuted });
+ return;
+ }
+ if (message.kind === "output-pcm") {
+ if (!(message.samples instanceof ArrayBuffer) || !Number.isSafeInteger(message.sequence) || !Number.isSafeInteger(message.playbackEpoch)) return;
+ const chunk = {
+ samples: new Float32Array(message.samples),
+ sequence: message.sequence,
+ playbackEpoch: message.playbackEpoch,
+ responseKey: typeof message.responseKey === "string" ? message.responseKey : "",
+ itemId: typeof message.itemId === "string" ? message.itemId : "",
+ contentIndex: Number.isSafeInteger(message.contentIndex) && message.contentIndex >= 0 ? message.contentIndex : 0,
+ sampleOffset: Number.isSafeInteger(message.sampleOffset) && message.sampleOffset >= 0 ? message.sampleOffset : 0,
+ position: 0,
+ };
+ if (chunk.playbackEpoch !== this.playbackEpoch || this.stopped) {
+ this.port.postMessage({ kind: "chunk-dropped", sequence: chunk.sequence });
+ return;
+ }
+ this.playbackQueue.push(chunk);
+ return;
+ }
+ if (message.kind === "interrupt") {
+ this.playbackEpoch = Number.isSafeInteger(message.playbackEpoch) ? message.playbackEpoch : this.playbackEpoch + 1;
+ const cursors = this.cursorSnapshot();
+ this.dropQueuedPlayback();
+ this.port.postMessage({ kind: "interruption-applied", requestId: message.requestId, playbackEpoch: this.playbackEpoch, cursors });
+ return;
+ }
+ if (message.kind === "playback-reset") {
+ if (Number.isSafeInteger(message.playbackEpoch) && message.playbackEpoch >= this.playbackEpoch) {
+ this.playbackEpoch = message.playbackEpoch;
+ this.playbackCursors.clear();
+ this.dropQueuedPlayback();
+ }
+ return;
+ }
+ if (message.kind === "release") {
+ this.stopped = true;
+ this.captureMuted = true;
+ this.captureOffset = 0;
+ this.dropQueuedPlayback();
+ this.port.postMessage({ kind: "media-stopped" });
+ }
+ }
+
+ process(inputs, outputs) {
+ const output = outputs[0]?.[0];
+ if (output) output.fill(0);
+ if (!this.stopped && !this.captureMuted) this.capture(inputs[0]?.[0]);
+ if (!this.stopped && output) this.render(output);
+ return true;
+ }
+
+ capture(input) {
+ if (!input) return;
+ let sourceOffset = 0;
+ while (sourceOffset < input.length) {
+ const count = Math.min(this.captureFrameSize - this.captureOffset, input.length - sourceOffset);
+ this.captureFrame.set(input.subarray(sourceOffset, sourceOffset + count), this.captureOffset);
+ this.captureOffset += count;
+ sourceOffset += count;
+ if (this.captureOffset === this.captureFrameSize) {
+ const samples = this.captureFrame;
+ this.captureFrame = new Float32Array(this.captureFrameSize);
+ this.captureOffset = 0;
+ this.port.postMessage({ kind: "input-frame", sampleRate, captureEpoch: this.captureEpoch, samples: samples.buffer }, [samples.buffer]);
+ }
+ }
+ }
+
+ render(output) {
+ const sourceStep = PLAYBACK_SAMPLE_RATE / sampleRate;
+ for (let outputIndex = 0; outputIndex < output.length; outputIndex += 1) {
+ if (!this.currentChunk) this.currentChunk = this.playbackQueue.shift() ?? null;
+ const chunk = this.currentChunk;
+ if (!chunk) break;
+ if (chunk.playbackEpoch !== this.playbackEpoch) {
+ this.finishChunk(chunk, true);
+ this.currentChunk = null;
+ outputIndex -= 1;
+ continue;
+ }
+ const position = chunk.position;
+ const leftIndex = Math.floor(position);
+ const rightIndex = Math.min(chunk.samples.length - 1, leftIndex + 1);
+ const fraction = position - leftIndex;
+ const left = chunk.samples[leftIndex] ?? 0;
+ const right = chunk.samples[rightIndex] ?? left;
+ output[outputIndex] = left + (right - left) * fraction;
+ chunk.position += sourceStep;
+ if (chunk.itemId) {
+ const cursorKey = `${chunk.itemId}\u0000${chunk.contentIndex}`;
+ const playedSamples = chunk.sampleOffset + Math.min(chunk.samples.length, Math.floor(chunk.position));
+ const previous = this.playbackCursors.get(cursorKey);
+ this.playbackCursors.set(cursorKey, {
+ itemId: chunk.itemId,
+ contentIndex: chunk.contentIndex,
+ playedSamples: Math.max(previous?.playedSamples ?? 0, playedSamples),
+ sampleRate: PLAYBACK_SAMPLE_RATE,
+ });
+ while (this.playbackCursors.size > 64) {
+ const oldestKey = this.playbackCursors.keys().next().value;
+ if (oldestKey === undefined) break;
+ this.playbackCursors.delete(oldestKey);
+ }
+ }
+ if (chunk.position >= chunk.samples.length) {
+ this.finishChunk(chunk, false);
+ this.currentChunk = null;
+ }
+ }
+ this.renderedSinceReport += output.length;
+ if (this.renderedSinceReport >= sampleRate / 10) {
+ this.renderedSinceReport = 0;
+ this.port.postMessage({ kind: "playback-position", cursors: this.cursorSnapshot() });
+ }
+ }
+
+ finishChunk(chunk, dropped) {
+ this.port.postMessage({ kind: dropped ? "chunk-dropped" : "chunk-played", sequence: chunk.sequence });
+ }
+
+ dropQueuedPlayback() {
+ if (this.currentChunk) this.finishChunk(this.currentChunk, true);
+ this.currentChunk = null;
+ for (const chunk of this.playbackQueue) this.finishChunk(chunk, true);
+ this.playbackQueue.length = 0;
+ }
+
+ cursorSnapshot() {
+ return [...this.playbackCursors.values()].slice(-64);
+ }
+}
+
+registerProcessor("pi-live-pcm", PiLivePcmProcessor);
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index 7b871d2d1..d75f16756 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -292,6 +292,7 @@ declare global {
piDesktop?: {
invoke: <T = unknown>(channel: string, ...args: unknown[]) => Promise<Result<T>>;
on: (channel: string, listener: (...args: unknown[]) => void) => () => void;
+ onLiveVoicePort?: () => () => void;
channels: typeof IPC;
platform: NodeJS.Platform;
/** Authoritative OS locale passed from the main process at window creation. */
diff --git a/apps/desktop/src/styles/voice.css b/apps/desktop/src/styles/voice.css
index c4e4cafd7..631e61ba1 100644
--- a/apps/desktop/src/styles/voice.css
+++ b/apps/desktop/src/styles/voice.css
@@ -113,4 +113,57 @@
max-width: none;
}
+.live-voice-control {
+ position: relative;
+}
+
+.live-voice-panel {
+ position: absolute;
+ left: 0;
+ bottom: calc(100% + 8px);
+ z-index: 20;
+ display: grid;
+ width: min(360px, calc(100vw - 32px));
+ gap: 10px;
+ padding: 12px;
+}
+
+.live-voice-panel-heading,
+.live-voice-actions {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+}
+
+.live-voice-provider,
+.live-voice-hint {
+ color: var(--color-text-secondary, #999);
+ font-size: var(--text-sm);
+}
+
+.live-voice-error {
+ color: var(--color-danger, #ef4444);
+ font-size: var(--text-sm);
+}
+
+.live-voice-transcripts {
+ display: grid;
+ gap: 6px;
+ max-height: 180px;
+ overflow: auto;
+ padding: 8px;
+ border-radius: var(--radius-xs);
+ background: var(--color-surface, #171717);
+ font-size: var(--text-sm);
+ white-space: pre-wrap;
+}
+
+.live-voice-transcripts p {
+ margin: 0;
+}
+
+.live-voice-transcripts p[data-role="user"] {
+ color: var(--color-text-secondary, #999);
+}
diff --git a/apps/desktop/test/live-voice-codex-sdp.test.mjs b/apps/desktop/test/live-voice-codex-sdp.test.mjs
new file mode 100644
index 000000000..34da5022f
--- /dev/null
+++ b/apps/desktop/test/live-voice-codex-sdp.test.mjs
@@ -0,0 +1,36 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { createServer } from "vite";
+
+test("Codex Live validates and bounds SDP negotiation payloads", async (t) => {
+ const server = await createServer({
+ root: fileURLToPath(new URL("..", import.meta.url)),
+ configFile: false,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ t.after(() => server.close());
+ const { extractCodexSdpAnswer, normalizeCodexSdp, readResponseTextBounded } = await server.ssrLoadModule("/electron/main/live-voice/codex-sdp.ts");
+ const { responseCodeError } = await server.ssrLoadModule("/electron/main/live-voice/websocket-errors.ts");
+
+ assert.equal(normalizeCodexSdp("v=0\r\n"), "v=0\r\n");
+ assert.equal(extractCodexSdpAnswer('{"sdp":"v=0\\r\\n"}'), "v=0\r\n");
+ assert.throws(() => normalizeCodexSdp("v=1\r\n"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ assert.throws(() => normalizeCodexSdp("v=0\0\r\n"), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ assert.throws(() => extractCodexSdpAnswer('{"sdp":"v=0\\r\\n","debug":"no"}'), { errorCode: "LIVE_PROTOCOL_ERROR" });
+
+ const bounded = new Response(new ReadableStream({
+ start(controller) {
+ controller.enqueue(new TextEncoder().encode("v=0\r\n"));
+ controller.enqueue(new TextEncoder().encode("x".repeat(8)));
+ controller.close();
+ },
+ }));
+ await assert.rejects(readResponseTextBounded(bounded, 8), { errorCode: "LIVE_PROTOCOL_ERROR" });
+ assert.deepEqual(responseCodeError(401), { code: "LIVE_AUTH_REQUIRED", retriable: false });
+ assert.deepEqual(responseCodeError(403), { code: "LIVE_ACCESS_DENIED", retriable: false });
+ assert.deepEqual(responseCodeError(429), { code: "LIVE_RATE_LIMITED", retriable: true });
+ assert.deepEqual(responseCodeError(503), { code: "LIVE_NETWORK_ERROR", retriable: true });
+});
diff --git a/apps/desktop/test/live-voice-controller.test.mjs b/apps/desktop/test/live-voice-controller.test.mjs
new file mode 100644
index 000000000..8019929cb
--- /dev/null
+++ b/apps/desktop/test/live-voice-controller.test.mjs
@@ -0,0 +1,179 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { createServer } from "vite";
+
+test("renderer and Main complete a Codex Live user path without invoking an Agent", async (t) => {
+ const originalWindowDescriptor = Object.getOwnPropertyDescriptor(globalThis, "window");
+ const originalNavigatorDescriptor = Object.getOwnPropertyDescriptor(globalThis, "navigator");
+ const listeners = new Map();
+ const sentDataChannelMessages = [];
+ const tracks = [{ enabled: true, stopped: false, stop() { this.stopped = true; } }];
+ const stream = { getAudioTracks: () => tracks, getTracks: () => tracks };
+ const settings = {
+ liveVoice: {
+ enabled: true,
+ selectedBindingId: "codex-main",
+ bindings: [{ id: "codex-main", adapterId: "codex-live", providerId: "codex-account-a", voice: "cove" }],
+ },
+ voice: { enabled: true, deviceId: null, languages: ["en"], chineseVariant: "simplified", modelId: "local-model" },
+ };
+ const provider = {
+ id: "codex-account-a", name: "Codex", vendorKey: "openai-codex", enabled: true,
+ authKind: "oauth", hasSecret: true, models: [], supportsReasoning: false, supportedThinkingLevels: [],
+ };
+ const owner = { webContentsId: 8, frameProcessId: 2, frameRoutingId: 3, url: "file:///app/index.html" };
+ const sentViews = [];
+ const sentControls = [];
+ const sentTranscripts = [];
+ const createdAdapters = [];
+ let service;
+
+ const emit = (channel, payload) => {
+ for (const listener of listeners.get(channel) ?? []) listener(payload);
+ };
+ const ipc = {
+ platform: "linux",
+ channels: {},
+ on(channel, listener) {
+ const channelListeners = listeners.get(channel) ?? new Set();
+ channelListeners.add(listener);
+ listeners.set(channel, channelListeners);
+ return () => channelListeners.delete(listener);
+ },
+ onLiveVoicePort: () => () => undefined,
+ invoke: async (channel, ...args) => {
+ let data;
+ switch (channel) {
+ case "pi-desktop/settings/get": data = settings; break;
+ case "pi-desktop/voice/live/status": data = await service.status(); break;
+ case "pi-desktop/voice/live/prepare": data = await service.prepare(owner, args[0]); break;
+ case "pi-desktop/voice/live/connect": data = await service.connect(owner, args[0]); break;
+ case "pi-desktop/voice/live/setMuted": data = await service.setMuted(owner, args[0]); break;
+ case "pi-desktop/voice/live/reportMedia": data = service.reportMedia(owner, args[0]); break;
+ case "pi-desktop/voice/live/reportPlayback": service.reportPlayback(owner, args[0]); data = { ok: true }; break;
+ case "pi-desktop/voice/live/reportDelegation": data = await service.reportDelegation(owner, args[0]); break;
+ case "pi-desktop/voice/live/reportControlApplied": service.reportControlApplied(owner, args[0]); data = { ok: true }; break;
+ case "pi-desktop/voice/live/end": data = await service.end(owner, args[0]); break;
+ case "pi-desktop/voice/live/heartbeat": data = service.heartbeat(owner, args[0].callId); break;
+ default: throw new Error(`Unexpected IPC request: ${channel}`);
+ }
+ return { ok: true, data };
+ },
+ };
+ Object.defineProperty(globalThis, "window", { configurable: true, value: {
+ piDesktop: ipc,
+ location: { origin: "null" },
+ addEventListener() {},
+ } });
+ Object.defineProperty(globalThis, "navigator", { configurable: true, value: { mediaDevices: { getUserMedia: async () => stream } } });
+ const originalPeer = globalThis.RTCPeerConnection;
+ const peerInstances = [];
+ class FakeDataChannel {
+ readyState = "open";
+ onmessage = null;
+ onerror = null;
+ send(value) { sentDataChannelMessages.push(value); }
+ close() { this.readyState = "closed"; }
+ }
+ class FakePeer extends EventTarget {
+ connectionState = "new";
+ iceGatheringState = "complete";
+ localDescription = null;
+ channel = new FakeDataChannel();
+ createDataChannel() { return this.channel; }
+ addTrack() {}
+ async createOffer() { return { type: "offer", sdp: "v=0\r\n" }; }
+ async setLocalDescription(description) { this.localDescription = description; }
+ async setRemoteDescription() {
+ this.connectionState = "connected";
+ this.dispatchEvent(new Event("connectionstatechange"));
+ }
+ close() {
+ this.connectionState = "closed";
+ this.dispatchEvent(new Event("connectionstatechange"));
+ }
+ constructor() { super(); peerInstances.push(this); }
+ }
+ globalThis.RTCPeerConnection = FakePeer;
+ t.after(() => {
+ if (originalWindowDescriptor) Object.defineProperty(globalThis, "window", originalWindowDescriptor);
+ else delete globalThis.window;
+ if (originalNavigatorDescriptor) Object.defineProperty(globalThis, "navigator", originalNavigatorDescriptor);
+ else delete globalThis.navigator;
+ if (originalPeer === undefined) delete globalThis.RTCPeerConnection;
+ else globalThis.RTCPeerConnection = originalPeer;
+ });
+
+ const server = await createServer({
+ root: fileURLToPath(new URL("..", import.meta.url)),
+ configFile: false,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ t.after(() => server.close());
+ let controller;
+ try {
+ const { LiveCallService } = await server.ssrLoadModule("/electron/main/live-voice/call-service.ts");
+ const { getLiveCallController } = await server.ssrLoadModule("/src/features/voice/live/live-call-controller.ts");
+ service = new LiveCallService({
+ loadSettings: async () => settings,
+ authResolver: {
+ provider: async (id) => id === provider.id ? { provider } : null,
+ resolve: async () => ({ provider, auth: { kind: "codex-oauth", accessToken: "opaque-test-token", accountId: "account-a" } }),
+ },
+ createAdapter: (context) => {
+ createdAdapters.push(context);
+ return { adapterId: "codex-live", mediaKind: "webrtc", connect: async () => ({ answerSdp: "v=0\r\n" }), close: async () => undefined };
+ },
+ createPcmBridge: () => { throw new Error("Codex path created a PCM bridge"); },
+ sendView: (_owner, view) => { sentViews.push(view); emit("pi-desktop/voice/live/event/changed", view); },
+ sendControl: (_owner, event) => { sentControls.push(event); emit("pi-desktop/voice/live/event/control", event); },
+ sendTranscript: (_owner, event) => { sentTranscripts.push(event); emit("pi-desktop/voice/live/event/transcript", event); },
+ ownerAlive: () => true,
+ acquireMicrophone: () => () => undefined,
+ });
+ controller = getLiveCallController();
+ await controller.refreshStatus();
+ settings.liveVoice.selectedBindingId = undefined;
+ await controller.refreshStatus();
+ await assert.rejects(controller.start(), (error) => error.code === "LIVE_NOT_CONFIGURED");
+ settings.liveVoice.selectedBindingId = "codex-main";
+ await controller.refreshStatus();
+ await controller.start();
+ assert.equal(controller.getSnapshot().call.phase, "connected");
+ assert.equal(controller.getSnapshot().call.muted, true);
+ assert.equal(peerInstances.length, 1);
+ const connectedView = sentViews.at(-1);
+ emit("pi-desktop/voice/live/event/changed", { ...connectedView, revision: connectedView.revision - 1, phase: "failed" });
+ assert.equal(controller.getSnapshot().call.phase, "connected");
+
+ peerInstances[0].channel.onmessage({ data: JSON.stringify({ type: "output_transcript.added", text: "Hello from the voice provider." }) });
+ assert.equal(controller.getSnapshot().transcripts.at(-1).text, "Hello from the voice provider.");
+ peerInstances[0].channel.onmessage({ data: JSON.stringify({
+ type: "delegation.created",
+ item: { type: "delegation", target: "client", id: "request-1", content: [{ type: "input_text", text: "Read a local file" }] },
+ }) });
+ await new Promise((resolve) => setImmediate(resolve));
+ assert.equal(sentControls.at(-1).kind, "reject-delegation");
+ assert.match(sentDataChannelMessages.at(-1), /did not create a new task/);
+ assert.equal(createdAdapters.length, 1);
+
+ await controller.toggleMute();
+ assert.equal(controller.getSnapshot().call.muted, false);
+ assert.equal(tracks[0].enabled, true);
+ await controller.toggleMute();
+ assert.equal(controller.getSnapshot().call.muted, true);
+ assert.equal(tracks[0].enabled, false);
+
+ await controller.end();
+ assert.equal(controller.getSnapshot().call.phase, "ended");
+ assert.equal(tracks[0].stopped, true);
+ assert.equal(sentViews.at(-1).phase, "ended");
+ assert.equal(controller.getSnapshot().transcripts.length, 1);
+ assert.doesNotMatch(JSON.stringify(controller.getSnapshot()), /opaque-test-token/);
+ } finally {
+ if (controller) await controller.end().catch(() => undefined);
+ }
+});
diff --git a/apps/desktop/test/live-voice-controls.test.mjs b/apps/desktop/test/live-voice-controls.test.mjs
new file mode 100644
index 000000000..797d948eb
--- /dev/null
+++ b/apps/desktop/test/live-voice-controls.test.mjs
@@ -0,0 +1,42 @@
+import assert from "node:assert/strict";
+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 originalWindow = Object.getOwnPropertyDescriptor(globalThis, "window");
+ Object.defineProperty(globalThis, "window", {
+ configurable: true,
+ value: {
+ location: { origin: "http://localhost" },
+ addEventListener() {},
+ removeEventListener() {},
+ piDesktop: {
+ on: () => () => undefined,
+ invoke: async () => ({ ok: true, data: { voice: { enabled: false, languages: [] } } }),
+ },
+ },
+ });
+ t.after(() => {
+ if (originalWindow) Object.defineProperty(globalThis, "window", originalWindow);
+ else delete globalThis.window;
+ });
+
+ const server = await createServer({
+ root: fileURLToPath(new URL("..", import.meta.url)),
+ configFile: false,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ t.after(() => server.close());
+ 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 }));
+
+ assert.match(html, /aria-label="liveVoice\.start"/);
+ assert.match(html, /aria-pressed="false"/);
+ assert.match(html, /aria-haspopup="dialog"/);
+ assert.doesNotMatch(html, /<button[^>]*disabled(?:="")?/);
+});
diff --git a/apps/desktop/test/live-voice-permission.test.mjs b/apps/desktop/test/live-voice-permission.test.mjs
new file mode 100644
index 000000000..62637ca01
--- /dev/null
+++ b/apps/desktop/test/live-voice-permission.test.mjs
@@ -0,0 +1,62 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { createServer } from "vite";
+
+test("Live Voice media permission requires the trusted main frame and an active microphone lease", async (t) => {
+ const previousRendererUrl = process.env.ELECTRON_RENDERER_URL;
+ process.env.ELECTRON_RENDERER_URL = "http://localhost:5173/";
+ t.after(() => {
+ if (previousRendererUrl === undefined) delete process.env.ELECTRON_RENDERER_URL;
+ else process.env.ELECTRON_RENDERER_URL = previousRendererUrl;
+ });
+ const server = await createServer({
+ root: fileURLToPath(new URL("..", import.meta.url)),
+ configFile: false,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ t.after(() => server.close());
+ const { installLiveMicrophonePermissionHandlers } = await server.ssrLoadModule("/electron/main/live-voice/microphone-permissions.ts");
+
+ const trustedUrl = "http://localhost:5173/";
+ const contents = {
+ id: 4,
+ isDestroyed: () => false,
+ getURL: () => trustedUrl,
+ mainFrame: { url: trustedUrl, processId: 5, routingId: 6 },
+ };
+ const window = { isDestroyed: () => false, webContents: contents };
+ const handlers = {};
+ let leaseActive = true;
+ installLiveMicrophonePermissionHandlers({
+ targetSession: {
+ setPermissionRequestHandler: (handler) => { handlers.request = handler; },
+ setPermissionCheckHandler: (handler) => { handlers.check = handler; },
+ },
+ getMainWindow: () => window,
+ hasReservation: () => leaseActive,
+ });
+
+ const requestDecision = (details, permission = "media", requester = contents) => {
+ let decision = false;
+ handlers.request(requester, permission, (value) => { decision = value; }, details);
+ return decision;
+ };
+ const checkDecision = (details, origin = "http://localhost:5173", permission = "media", requester = contents) =>
+ handlers.check(requester, permission, origin, details);
+
+ assert.equal(requestDecision({ requestingUrl: trustedUrl, isMainFrame: true, mediaTypes: ["audio"] }), true);
+ assert.equal(checkDecision({ mediaType: "unknown" }), true);
+ assert.equal(checkDecision({ mediaType: "audio" }), true);
+ assert.equal(requestDecision({ requestingUrl: trustedUrl, isMainFrame: true, mediaTypes: ["audio", "video"] }), false);
+ assert.equal(requestDecision({ requestingUrl: trustedUrl, isMainFrame: false, mediaTypes: ["audio"] }), false);
+ assert.equal(requestDecision({ requestingUrl: "https://outside.example", isMainFrame: true, mediaTypes: ["audio"] }), false);
+ assert.equal(checkDecision({ mediaType: "audio" }, "https://outside.example"), false);
+ assert.equal(requestDecision({ requestingUrl: trustedUrl, isMainFrame: true, mediaTypes: ["audio"] }, "notifications"), false);
+ assert.equal(requestDecision({ requestingUrl: trustedUrl, isMainFrame: true, mediaTypes: ["audio"] }, "media", {}), false);
+ leaseActive = false;
+ assert.equal(requestDecision({ requestingUrl: trustedUrl, isMainFrame: true, mediaTypes: ["audio"] }), false);
+ assert.equal(checkDecision({ mediaType: "audio" }), false);
+});
diff --git a/apps/desktop/test/live-voice-service.test.mjs b/apps/desktop/test/live-voice-service.test.mjs
new file mode 100644
index 000000000..316fbcd70
--- /dev/null
+++ b/apps/desktop/test/live-voice-service.test.mjs
@@ -0,0 +1,248 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { fileURLToPath } from "node:url";
+import { createServer } from "vite";
+
+const owner = { webContentsId: 4, frameProcessId: 1, frameRoutingId: 2, url: "file:///app/index.html" };
+const otherOwner = { ...owner, frameRoutingId: 3 };
+const binding = { id: "codex-main", adapterId: "codex-live", providerId: "codex-account-a", voice: "cove" };
+const requestId = "3d7d68a1-6283-4cfb-a40e-2dd1a74fd19f";
+
+async function loadModules(t) {
+ const server = await createServer({
+ root: fileURLToPath(new URL("..", import.meta.url)),
+ configFile: false,
+ server: { middlewareMode: true, hmr: false, ws: false },
+ appType: "custom",
+ optimizeDeps: { noDiscovery: true, include: [] },
+ });
+ t.after(() => server.close());
+ return {
+ ...(await server.ssrLoadModule("/electron/main/live-voice/call-service.ts")),
+ ...(await server.ssrLoadModule("/electron/main/live-voice/microphone-lease.ts")),
+ };
+}
+
+function dependencies(overrides = {}) {
+ const state = {
+ events: [],
+ controls: [],
+ transcripts: [],
+ adapters: [],
+ releasedMic: [],
+ settings: { liveVoice: { enabled: true, selectedBindingId: binding.id, bindings: [binding] }, voice: { enabled: false } },
+ };
+ const provider = {
+ id: binding.providerId,
+ name: "Codex",
+ vendorKey: "openai-codex",
+ enabled: true,
+ authKind: "oauth",
+ hasSecret: true,
+ models: [],
+ supportsReasoning: false,
+ supportedThinkingLevels: [],
+ };
+ const deps = {
+ loadSettings: async () => state.settings,
+ authResolver: {
+ provider: async (providerId) => providerId === provider.id ? { provider } : null,
+ resolve: async () => ({ provider, auth: { kind: "codex-oauth", accessToken: "test-token", accountId: "account-a" } }),
+ },
+ createAdapter: (context) => {
+ state.adapters.push(context);
+ return {
+ adapterId: "codex-live",
+ mediaKind: "webrtc",
+ connect: async ({ offerSdp }) => {
+ assert.equal(offerSdp, "v=0\r\n");
+ return { answerSdp: "v=0\r\n" };
+ },
+ close: async () => undefined,
+ };
+ },
+ createPcmBridge: () => { throw new Error("Codex must not create a PCM bridge"); },
+ sendView: (_owner, view) => state.events.push(view),
+ sendControl: (_owner, event) => state.controls.push(event),
+ sendTranscript: (_owner, event) => state.transcripts.push(event),
+ ownerAlive: () => true,
+ acquireMicrophone: (callId) => () => state.releasedMic.push(callId),
+ ...overrides,
+ };
+ return { deps, state };
+}
+
+test("Live call follows prepare, connect, mute, in-memory transcript, reject-only delegation, and end", async (t) => {
+ const { LiveCallService } = await loadModules(t);
+ const { deps, state } = dependencies();
+ const service = new LiveCallService(deps);
+ const status = await service.status();
+ assert.equal(status.enabled, true);
+ assert.equal(status.bindings[0].selectable, true);
+
+ const prepared = await service.prepare(owner, { requestId, bindingId: binding.id, expectedSettingsRevision: status.settingsRevision, initialMuted: true });
+ assert.equal(service.hasMicrophoneReservation(owner), true);
+ assert.equal(service.hasMicrophoneReservation(otherOwner), false);
+ let ended = false;
+ t.after(async () => {
+ if (ended) return;
+ const ending = service.end(owner, { callId: prepared.callId, reason: "user-ended" }).catch(() => undefined);
+ try { service.reportMedia(owner, { callId: prepared.callId, kind: "released" }); } catch { /* the service may already have cleaned up */ }
+ await ending;
+ });
+ const connected = await service.connect(owner, { callId: prepared.callId, offerSdp: "v=0\r\n" });
+ assert.equal(connected.answerSdp, "v=0\r\n");
+ service.reportMedia(owner, { callId: prepared.callId, kind: "microphone-active", active: true });
+ service.reportMedia(owner, { callId: prepared.callId, kind: "phase", phase: "connected" });
+
+ const muted = await service.setMuted(owner, { callId: prepared.callId, muted: false, captureEpoch: 1 });
+ assert.equal(muted.muted, false);
+ await assert.rejects(service.setMuted(otherOwner, { callId: prepared.callId, muted: true, captureEpoch: 2 }), { errorCode: "LIVE_INVALID_OWNER" });
+
+ state.adapters[0].onEvent({ kind: "transcript", id: "part-1", role: "assistant", text: "hello", final: false });
+ state.adapters[0].onEvent({ kind: "transcript", id: "part-1", role: "assistant", text: "hello there", final: true });
+ assert.equal(state.transcripts.length, 2);
+ assert.equal(state.transcripts[1].segment.text, "hello there");
+
+ await service.reportDelegation(owner, { callId: prepared.callId, delegationId: "delegation-1", instruction: "Read the project files" });
+ assert.equal(state.controls.at(-1).kind, "reject-delegation");
+ assert.equal(state.controls.at(-1).reason, "EXECUTION_NOT_CONNECTED");
+ assert.equal(state.adapters.length, 1, "delegation does not create another runtime or agent");
+ service.reportControlApplied(owner, { callId: prepared.callId, actionId: state.controls.at(-1).actionId, applied: true });
+
+ const endPromise = service.end(owner, { callId: prepared.callId, reason: "user-ended" });
+ assert.equal(state.controls.at(-1).kind, "release-media");
+ service.reportMedia(owner, { callId: prepared.callId, kind: "released" });
+ await endPromise;
+ ended = true;
+ assert.equal(state.releasedMic.length, 1);
+ assert.equal(service.hasMicrophoneReservation(owner), false);
+ assert.equal((await service.status()).call.phase, "ended");
+});
+
+test("PCM Live service waits for the port lease, gates capture, and forwards output without exposing auth", async (t) => {
+ const { LiveCallService } = await loadModules(t);
+ const pcmBinding = { id: "gemini-main", adapterId: "gemini-live", providerId: "google-key", modelId: "gemini-live-model", voice: "Kore" };
+ const { deps, state } = dependencies();
+ state.settings.liveVoice = { enabled: true, selectedBindingId: pcmBinding.id, bindings: [pcmBinding] };
+ const provider = {
+ id: pcmBinding.providerId, name: "Google", vendorKey: "google", enabled: true, authKind: "api_key",
+ apiStyle: "google_generative_ai", hasSecret: true, models: [], supportsReasoning: false, supportedThinkingLevels: [],
+ };
+ const inputFrames = [];
+ const outputFrames = [];
+ const bridgeConfig = {};
+ const bridge = {
+ portNonce: "a58f6ff6-e877-40b5-8476-f9dfe9650796",
+ ready: Promise.resolve(),
+ setMuted: async () => undefined,
+ sendOutput: (frame) => outputFrames.push(frame),
+ reportPlayback: () => undefined,
+ interrupt: async () => [],
+ requestRelease: async () => undefined,
+ close: () => undefined,
+ };
+ deps.authResolver.provider = async (providerId) => providerId === provider.id ? { provider } : null;
+ deps.authResolver.resolve = async () => ({ provider, auth: { kind: "api-key", apiKey: "secret-test-key", baseUrl: "https://generativelanguage.googleapis.com" } });
+ deps.createPcmBridge = (input) => { Object.assign(bridgeConfig, input); return bridge; };
+ deps.createAdapter = (context) => {
+ state.adapters.push(context);
+ return {
+ adapterId: "gemini-live",
+ mediaKind: "pcm",
+ connect: async () => ({}),
+ sendInputPcm: (bytes) => inputFrames.push(bytes),
+ close: async () => undefined,
+ };
+ };
+ const service = new LiveCallService(deps);
+ const status = await service.status();
+ assert.equal(status.bindings[0].selectable, true);
+ const pcmRequestId = "bd56d49e-aef0-47e1-a2df-630003fa0f35";
+ const prepared = await service.prepare(owner, {
+ requestId: pcmRequestId,
+ bindingId: pcmBinding.id,
+ expectedSettingsRevision: status.settingsRevision,
+ initialMuted: true,
+ });
+ assert.equal(prepared.mediaKind, "pcm");
+ assert.equal(prepared.inputSampleRate, 16000);
+ assert.equal(prepared.portNonce, bridge.portNonce);
+ assert.equal(bridgeConfig.inputSampleRate, 16000);
+ assert.equal(service.hasMicrophoneReservation(owner), true);
+
+ const bytes = new Uint8Array([1, 0, 2, 0]);
+ bridgeConfig.onInput(bytes, 0);
+ assert.equal(inputFrames.length, 0, "Main ignores input before the provider is connected and unmuted");
+ await service.connect(owner, { callId: prepared.callId });
+ service.reportMedia(owner, { callId: prepared.callId, kind: "microphone-active", active: true });
+ service.reportMedia(owner, { callId: prepared.callId, kind: "phase", phase: "connected" });
+ await service.setMuted(owner, { callId: prepared.callId, muted: false, captureEpoch: 1 });
+ bridgeConfig.onInput(bytes, 1);
+ assert.equal(inputFrames.length, 1);
+ state.adapters[0].onEvent({ kind: "audio", bytes, responseId: "response-1", itemId: "item-1", contentIndex: 0 });
+ assert.equal(outputFrames[0].responseId, "response-1");
+ assert.equal(JSON.stringify(state.events).includes("secret-test-key"), false);
+
+ const ending = service.end(owner, { callId: prepared.callId, reason: "user-ended" });
+ service.reportMedia(owner, { callId: prepared.callId, kind: "released" });
+ await ending;
+ assert.equal(service.hasMicrophoneReservation(owner), false);
+});
+
+test("an active binding cannot be rewritten by settings save, while unrelated settings remain writable", async (t) => {
+ const { LiveCallService } = await loadModules(t);
+ const { deps } = dependencies();
+ const service = new LiveCallService(deps);
+ const status = await service.status();
+ const prepared = await service.prepare(owner, { requestId, bindingId: binding.id, expectedSettingsRevision: status.settingsRevision, initialMuted: true });
+ let ended = false;
+ t.after(async () => {
+ if (ended) return;
+ const ending = service.end(owner, { callId: prepared.callId, reason: "user-ended" }).catch(() => undefined);
+ try { service.reportMedia(owner, { callId: prepared.callId, kind: "released" }); } catch { /* the service may already have cleaned up */ }
+ await ending;
+ });
+ const changedBinding = { ...binding, voice: "marin" };
+ assert.throws(() => service.beginSettingsWrite({ liveVoice: { enabled: true, selectedBindingId: binding.id, bindings: [changedBinding] }, voice: { enabled: false } }), { errorCode: "LIVE_SETTINGS_IN_USE" });
+ const release = service.beginSettingsWrite({ liveVoice: { enabled: true, selectedBindingId: binding.id, bindings: [binding] }, voice: { enabled: true } });
+ release();
+ const endPromise = service.end(owner, { callId: prepared.callId, reason: "user-ended" });
+ service.reportMedia(owner, { callId: prepared.callId, kind: "released" });
+ await endPromise;
+ ended = true;
+});
+
+test("cancel by requestId tombstones an in-flight prepare before it can acquire an adapter", async (t) => {
+ const { LiveCallService } = await loadModules(t);
+ const { deps, state } = dependencies();
+ const service = new LiveCallService(deps);
+ const status = await service.status();
+ let resolveSettings;
+ deps.loadSettings = () => new Promise((resolve) => { resolveSettings = resolve; });
+
+ const preparePromise = service.prepare(owner, { requestId, bindingId: binding.id, expectedSettingsRevision: status.settingsRevision, initialMuted: true });
+ assert.throws(() => service.beginSettingsWrite({ liveVoice: { enabled: true, selectedBindingId: binding.id, bindings: [{ ...binding, voice: "marin" }] } }), { errorCode: "LIVE_SETTINGS_IN_USE" });
+ const endPromise = service.end(owner, { requestId, reason: "user-cancelled-start" });
+ assert.equal(state.controls.at(-1).kind, "release-media");
+ service.reportMedia(owner, { callId: state.events.at(-1).callId, kind: "released" });
+ await endPromise;
+ resolveSettings(state.settings);
+ await assert.rejects(preparePromise, { errorCode: "LIVE_STALE_CALL" });
+ assert.equal(state.adapters.length, 0);
+ assert.equal(state.releasedMic.length, 1);
+});
+
+test("the microphone lease prevents Live and Dictation from owning capture together", async (t) => {
+ const { MicrophoneLeaseRegistry } = await loadModules(t);
+ let dictationActive = true;
+ const leases = new MicrophoneLeaseRegistry(() => dictationActive);
+ const releaseDictation = leases.acquire("dictation", "dictation-1");
+ assert.throws(() => leases.acquire("live", "live-1"), { errorCode: "LIVE_MICROPHONE_BUSY" });
+ releaseDictation();
+ dictationActive = false;
+ const releaseLive = leases.acquire("live", "live-1");
+ assert.equal(leases.isHeld(), true);
+ releaseLive();
+ assert.equal(leases.isHeld(), false);
+});
diff --git a/apps/desktop/test/rpc-lifecycle-contract.test.mjs b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
index 70388cce5..fce0bf595 100644
--- a/apps/desktop/test/rpc-lifecycle-contract.test.mjs
+++ b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
@@ -251,7 +251,7 @@ test("app quit waits for one idempotent teardown before allowing the follow-up q
test("settings writes validate without applying read defaults", () => {
assert.match(mainSource, /validateSettingsWrite\(settings\)/);
- assert.match(mainSource, /host\.call\("settings\.set", validatedSettings\)/);
+ assert.match(mainSource, /host\.call(?:<AppSettings>)?\("settings\.set", validatedSettings\)/);
assert.doesNotMatch(mainSource, /host\.call\("settings\.set", normalizedSettings\)/);
assert.match(apiSource, /export function validateSettingsWrite/);
assert.match(apiSource, /invoke\(IPC\.invoke\.settingsSet, validateSettingsWrite\(settings\)\)/);
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 293974441..9ca16b89d 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -6543,6 +6543,56 @@ mod tests {
assert_eq!(preserved["keybindings"]["openSearch"], Value::Null);
}
+ #[tokio::test]
+ async fn settings_set_round_trips_live_voice_without_changing_dictation_settings() {
+ let data_dir = tempfile::tempdir().unwrap();
+ let mut app_state = AppState::open(data_dir.path()).unwrap();
+ app_state.handshook = true;
+ let state = Arc::new(Mutex::new(app_state));
+ let tx = mpsc::unbounded_channel().0;
+ let live_voice = json!({
+ "enabled": false,
+ "selectedBindingId": "codex-main",
+ "bindings": [{
+ "id": "codex-main",
+ "adapterId": "codex-live",
+ "providerId": "codex-account-a",
+ "voice": "cove"
+ }]
+ });
+ let dictation = json!({
+ "enabled": true,
+ "deviceId": "microphone-1",
+ "languages": ["en"],
+ "chineseVariant": "simplified",
+ "modelId": "local-model"
+ });
+
+ handle_request(
+ state.clone(),
+ "settings.set",
+ json!({ "liveVoice": live_voice, "voice": dictation }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ handle_request(
+ state.clone(),
+ "settings.set",
+ json!({ "theme": "light" }),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ let stored = handle_request(state, "settings.get", json!({}), tx)
+ .await
+ .unwrap();
+
+ assert_eq!(stored["liveVoice"], live_voice);
+ assert_eq!(stored["voice"], dictation);
+ assert_eq!(stored["theme"], "light");
+ }
+
#[tokio::test]
async fn settings_set_preserves_stored_shell_when_shell_is_omitted() {
let Some(current_shell) = available_test_shell_id() else {
diff --git a/docs/implementation/live-voice-evidence.md b/docs/implementation/live-voice-evidence.md
new file mode 100644
index 000000000..73a3da53e
--- /dev/null
+++ b/docs/implementation/live-voice-evidence.md
@@ -0,0 +1,27 @@
+# Live Voice v1 Implementation Evidence
+
+This file records the local implementation baseline and verification limits.
+It contains no account credentials, tokens, audio or SDP.
+
+| Check | Evidence |
+|---|---|
+| Task base | Dedicated `codex/live-voice-v1` worktree created from `origin/main`; starting revision `86aa90b2a7436b014fa026d9b82cf4a50c9b4964`. |
+| Source checkout preservation | Primary checkout had pre-existing edits to `package.json` and three i18n locale files, plus the untracked original Live Voice spec. These remain in the primary checkout and are not part of this worktree. |
+| `pi-ai` version | Desktop package and lockfile use `@earendil-works/pi-ai` `0.87.1`; no dependency upgrade was made. |
+| OAuth entry point | `VendorOAuth.resolveAuth(providerId)` is the existing Main-process entry; Live injects the existing instance and uses the resolved `ModelAuth`. |
+| Codex account ID | Prefer the `chatgpt-account-id` header from resolved auth; otherwise read `chatgpt_account_id` from the `https://api.openai.com/auth` JWT claim. Reject disagreement and missing account identity. |
+| Settings owner | Host Core `settings.get/settings.set` stores app settings as a JSON object; `settings.set` merges top-level values. The Live Voice round-trip test preserves `voice` and unrelated settings. |
+| IPC owner gate | `apps/desktop/electron/main/live-voice/owner.ts` requires the current trusted main frame and derives ownership from Electron event metadata. Events are sent to that frame. |
+| Media permission gate | `apps/desktop/electron/main/live-voice/microphone-permissions.ts` installs both default-session permission handlers; only audio-only requests/checks from the exact trusted main frame with the active Live lease pass. A focused fixture covers subframes, other origins, video and missing leases. |
+| Microphone owners | Main `MicrophoneLeaseRegistry` arbitrates `dictation` and `live`; both Live and legacy Dictation acquire and release through it. |
+| PCM port binding | One-time nonce is required in the prepare result and first port `hello`; controller, preload and Main reject mismatched call/nonce ownership. |
+| Protocol profiles | Gemini setup/parser, Codex SDP bounds and OpenAI GA/compat Realtime configuration/event profiles have local fixture tests. Interrupted Realtime response IDs are tracked so late audio/completion cannot revive old playback. |
+| Network proxy | Codex HTTP uses Electron `net.fetch`; WebSockets use the default session proxy resolver and explicit DIRECT or supported HTTP/SOCKS5 tunnels. Unsupported proxy resolution fails closed. |
+| Reference sources | [PI-Desktop OAuth](https://github.com/vastsa/PI-Desktop/blob/f6a31c795ef902e128d11436f7d8dafd228ef6dc/apps/desktop/electron/main/oauth.ts), [PI-Desktop IPC types](https://github.com/vastsa/PI-Desktop/blob/f6a31c795ef902e128d11436f7d8dafd228ef6dc/apps/desktop/electron/main/ipc/types.ts), [PI-Desktop voice service](https://github.com/vastsa/PI-Desktop/blob/f6a31c795ef902e128d11436f7d8dafd228ef6dc/apps/desktop/electron/main/voice-service.ts), [PI-Desktop package](https://github.com/vastsa/PI-Desktop/blob/f6a31c795ef902e128d11436f7d8dafd228ef6dc/apps/desktop/package.json); [pi OAuth adapter](https://github.com/earendil-works/pi/blob/2b0a123de98318c2ff8069661721ce0c3794c34e/packages/ai/src/auth/oauth/openai-codex.ts) and [auth types](https://github.com/earendil-works/pi/blob/2b0a123de98318c2ff8069661721ce0c3794c34e/packages/ai/src/auth/types.ts); [Piwin Codex adapter](https://github.com/mimimaster/piwin/blob/67c8fc216030cfdcc85bfc8350da9070971ad78b/packages/voice/src/codex-live-adapter.ts) and [registration](https://github.com/mimimaster/piwin/blob/67c8fc216030cfdcc85bfc8350da9070971ad78b/packages/voice/src/codex-live-registration.ts), [Gemini adapter](https://github.com/mimimaster/piwin/blob/67c8fc216030cfdcc85bfc8350da9070971ad78b/packages/voice/src/gemini-live-adapter.ts), [OpenAI Realtime adapter](https://github.com/mimimaster/piwin/blob/67c8fc216030cfdcc85bfc8350da9070971ad78b/packages/voice/src/openai-realtime-adapter.ts); [Google Live API capabilities](https://ai.google.dev/gemini-api/docs/live-api/capabilities), [API reference](https://ai.google.dev/api/live), [WebSocket guide](https://ai.google.dev/gemini-api/docs/live-api/get-started-websocket), [session management](https://ai.google.dev/gemini-api/docs/live-api/session-management); [OpenAI Realtime guide](https://developers.openai.com/api/docs/guides/realtime), [conversations](https://developers.openai.com/api/docs/guides/realtime-conversations), [WebSocket guide](https://developers.openai.com/api/docs/guides/voice-websockets?voice-api=realtime); [Electron session permission handlers](https://www.electronjs.org/docs/latest/api/session#ses-setpermissionrequesthandlerhandler), [Electron MessagePortMain](https://www.electronjs.org/docs/latest/api/message-port-main), [MDN AudioWorklet](https://developer.mozilla.org/en-US/docs/Web/API/AudioWorklet). |
+| Automated verification | `pnpm build:js`, `pnpm lint`, desktop typecheck, `pnpm docs:check`, all targeted Live Voice tests, voice-runtime tests, shared tests, and Host Core format/test/clippy checks passed. `pnpm -r --if-present test` reported three desktop plugin source-resolution failures; see the row below. |
+| Full-suite exceptions | Desktop: 2,980/2,983 tests passed. `extensions-page`, `plugin-install-dialog`, and `plugin-runtime-risk` fail before assertions because raw Node import cannot resolve the pre-existing `../en/index.js` specifier to the `.ts` source. All nine Live Voice-focused desktop tests passed within the run. |
+| Real account/device validation | Not performed. No provider request or microphone prompt was started; access, entitlement, model availability, proxy route and physical playback remain unverified. |
+
+The upstream endpoint and model values are protocol references, not a promise
+of ongoing vendor support. Only automated local fixture evidence is claimed in
+this change.
diff --git a/docs/implementation/live-voice-progress.md b/docs/implementation/live-voice-progress.md
new file mode 100644
index 000000000..a271e8034
--- /dev/null
+++ b/docs/implementation/live-voice-progress.md
@@ -0,0 +1,23 @@
+# Live Voice v1 Progress
+
+- Implemented public settings/IPC DTOs, validation, error codes and the
+ `voice-runtime/live` pure PCM and wire-protocol entry.
+- Implemented Main authentication/provider resolution, Codex WebRTC
+ negotiation, Gemini and Realtime WebSocket adapters, bounded PCM bridge,
+ capture lease, owner checks, settings/provider invalidation and lifecycle
+ cleanup.
+- Implemented renderer window-lifetime controller, Codex WebRTC and PCM media
+ paths, mute/end/resume controls, transient transcript display, and Voice
+ settings for all three bindings.
+- Local implementation and fixture coverage are complete. The feature
+ remains `IMPLEMENTED_LIVE_VERIFICATION_PENDING` until real provider/account,
+ microphone-permission and hardware-playback acceptance is authorized and run.
+- Focused automated coverage exercises the Codex user path, PCM Main service
+ path, owner-bound microphone permissions, SDP bounds, accessible disabled
+ entry point, and protocol/PCM runtime behavior.
+- Full workspace tests ran. 2,980 desktop tests passed; three unrelated
+ plugin tests fail during Node source-module resolution because they import
+ `packages/i18n/src/locales/{en,index}.js`, which does not exist beside the
+ TypeScript source. The same trace is recorded in the delivery report.
+- Provider endpoints, entitlement, real device capture and audible playback
+ remain unverified. No live provider request or microphone prompt was started.
diff --git a/docs/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.md
index cd7b15617..3f5e824c9 100644
--- a/docs/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/spec/03-runtime/01-ipc-protocol.md
@@ -35,6 +35,7 @@ Principles:
| `menu` | Allowlisted application-menu commands and native editing/window actions |
| `notification` | Durable inbox list/read/clear, new/activated events, and native-notification sound cues |
| `stats` | Completed-turn token history (host RPC; dashboard is plugin-owned) |
+| `voice/live` | App-owned real-time calls, secret-free status/settings DTOs, and per-call media ports |
## 3. Channel Conventions
@@ -2360,3 +2361,38 @@ done and total for that phase, and the bytes when they are known. A long upload
of many resource objects is therefore not an interface with nothing to show.
Background polls report nothing, since only the manual path has a caller
watching.
+
+## 16. Live Voice API
+
+Live Voice is a main-window-only, app-owned call path described in
+[live-voice.md](live-voice.md). Its DTOs are defined in
+`packages/shared/src/types/live-voice.ts`; the preload exposes only the
+allowlisted channels below. Main derives the owner from the invoking trusted
+frame and sends call events only to that frame. No payload can supply an owner
+identity or credentials.
+
+| IPC channel | Direction | contract |
+|---|---|---|
+| `pi-desktop/voice/live/status` | Renderer → Main | redacted feature status, binding readiness and settings revision |
+| `pi-desktop/voice/live/prepare` | Renderer → Main | idempotent call preparation by request ID; synchronously reserves the shared microphone lease |
+| `pi-desktop/voice/live/connect` | Renderer → Main | connects a prepared call; Codex may include a bounded SDP offer |
+| `pi-desktop/voice/live/setMuted` | Renderer → Main | sets mute state with a monotonically increasing capture epoch |
+| `pi-desktop/voice/live/reportMedia` | Renderer → Main | reports capture, connection and release lifecycle; release acknowledgement is required before lease reuse |
+| `pi-desktop/voice/live/reportPlayback` | Renderer → Main | bounded list of played PCM cursors used for interruption/truncation |
+| `pi-desktop/voice/live/reportDelegation` | Renderer → Main | reports a provider-requested delegation; v1 rejects execution and never forwards it to Agent/MCP |
+| `pi-desktop/voice/live/reportControlApplied` | Renderer → Main | acknowledges a supported provider control or a rejected unsupported action |
+| `pi-desktop/voice/live/end` | Renderer → Main | idempotently ends an active call or cancels its pending request |
+| `pi-desktop/voice/live/heartbeat` | Renderer → Main | keeps the owning call alive while its renderer is responsive |
+| `pi-desktop/voice/live/event/changed` | Main → Renderer | redacted call phase, error, notice and activity updates |
+| `pi-desktop/voice/live/event/port` | Main → Renderer | transfers exactly one call-scoped `MessagePort` with its call ID and one-time nonce |
+| `pi-desktop/voice/live/event/control` | Main → Renderer | provider control request, limited to the explicit v1 control vocabulary |
+| `pi-desktop/voice/live/event/transcript` | Main → Renderer | transient bounded transcript event for the current call |
+
+The `MessagePort` is provisioned only after successful owner validation, then
+relayed by preload to the renderer window. The owner echoes the per-call nonce
+in its first `hello`; Main accepts the port once and only after the call ID and
+nonce match the prepared call. Its binary frames are bounded PCM audio, capture
+epochs, release acknowledgements, playback cursors and protocol readiness
+signals. It is not a generic IPC tunnel: it carries no provider
+credentials, arbitrary commands, workspace paths, Agent messages or durable
+transcripts. A port is closed on call end or owner loss.
diff --git a/docs/spec/03-runtime/08-error-codes.md b/docs/spec/03-runtime/08-error-codes.md
index 7d939ae5e..d3e2e29e9 100644
--- a/docs/spec/03-runtime/08-error-codes.md
+++ b/docs/spec/03-runtime/08-error-codes.md
@@ -309,6 +309,42 @@ codes surface through the same error object as any other call.
| `PAIRING_TOKEN_EXPIRED` | no | the single-use pairing token expired before pairing completed |
| `CAPABILITY_UNAVAILABLE` | no | an operation was requested for a capability the host advertised as unavailable (e.g. attachments, tool relay) |
+### 3.9 Live Voice
+
+Live Voice errors are returned through app-owned IPC and provider adapter
+events. They do not represent Agent turn failures. A retriable error means the
+user may retry the same call after the stated transient condition clears; it
+does not trigger automatic provider or billing fallback.
+
+| code | retriable | meaning |
+|---|---|---|
+| `LIVE_DISABLED` | no | Live Voice is disabled in settings |
+| `LIVE_NOT_CONFIGURED` | no | no valid Live Voice binding is selected |
+| `LIVE_PROVIDER_NOT_FOUND` | no | the selected Provider is missing, disabled, or changed while resolving credentials |
+| `LIVE_AUTH_KIND_UNSUPPORTED` | no | the selected Provider credential type is incompatible with the adapter |
+| `LIVE_AUTH_REQUIRED` | no | required OAuth or API-key credentials are absent or rejected |
+| `LIVE_ACCOUNT_ID_MISSING` | no | Codex OAuth account identity is absent or inconsistent |
+| `LIVE_ACCESS_DENIED` | no | the provider denied access or entitlement |
+| `LIVE_RATE_LIMITED` | yes | the provider returned a rate-limit response |
+| `LIVE_PROTOCOL_UNSUPPORTED` | no | endpoint, model, or requested protocol profile is unsupported |
+| `LIVE_PROTOCOL_ERROR` | no | a provider or IPC message is malformed or violates the selected protocol |
+| `LIVE_ALREADY_ACTIVE` | no | another Live Voice call or microphone-release quarantine owns the single-call slot |
+| `LIVE_REQUEST_CONFLICT` | no | an idempotency request ID was reused with different call parameters |
+| `LIVE_SETTINGS_IN_USE` | no | settings changed during preparation or the active binding cannot be rewritten |
+| `LIVE_MEDIA_RELEASE_UNCONFIRMED` | no | renderer media release was not acknowledged; Main quarantines the microphone lease |
+| `LIVE_STALE_CALL` | no | the call, request, or capture epoch is no longer current |
+| `LIVE_INVALID_OWNER` | no | IPC or media-port ownership does not match the trusted main frame |
+| `LIVE_MICROPHONE_BUSY` | no | Dictation, another Live call, or an unconfirmed prior release owns the shared capture lease |
+| `LIVE_MICROPHONE_DENIED` | no | the user or operating system denied microphone permission |
+| `LIVE_MICROPHONE_UNAVAILABLE` | no | no usable microphone device is available |
+| `LIVE_MEDIA_UNSUPPORTED` | no | required browser media or AudioWorklet support is unavailable |
+| `LIVE_PLAYBACK_BLOCKED` | maybe | browser audio playback needs a user gesture or could not resume |
+| `LIVE_TIMEOUT` | yes | a bounded startup, handshake, heartbeat, control, or cleanup stage timed out |
+| `LIVE_NETWORK_ERROR` | yes | a transient provider transport connection failed |
+| `LIVE_NETWORK_POLICY_UNSUPPORTED` | no | the desktop proxy route cannot be represented safely by the Live transport |
+| `LIVE_AUDIO_BACKPRESSURE` | no | bounded PCM or playback credits were exhausted |
+| `LIVE_EXECUTION_NOT_CONNECTED` | no | a provider requested an unsupported function/delegation execution path |
+
## 4. Mapping rules
### Host RPC numeric → AppError.code
diff --git a/docs/spec/03-runtime/README.md b/docs/spec/03-runtime/README.md
index 6a79d719e..0977eed25 100644
--- a/docs/spec/03-runtime/README.md
+++ b/docs/spec/03-runtime/README.md
@@ -22,6 +22,7 @@
| [18-line-anchored-edit-contract.md](18-line-anchored-edit-contract.md) | Line-anchored Edit contract |
| [19-remote-agent-control-protocol.md](19-remote-agent-control-protocol.md) | Remote Agent Control Protocol |
| [20-speech.md](20-speech.md) | Host speech (ASR/TTS) |
+| [live-voice.md](live-voice.md) | App-owned real-time voice calls |
- [Image generation and editing](21-image-generation.md)
- [Portable configuration sync](22-config-sync.md)
diff --git a/docs/spec/03-runtime/live-voice.md b/docs/spec/03-runtime/live-voice.md
new file mode 100644
index 000000000..b9d2a38c3
--- /dev/null
+++ b/docs/spec/03-runtime/live-voice.md
@@ -0,0 +1,109 @@
+# Live Voice v1
+
+## Scope
+
+Live Voice is an optional, app-owned real-time audio path. It is separate
+from local Dictation and Host Speech, and is disabled by default. v1 supports
+three explicit bindings:
+
+| Adapter | Credential owner | Transport |
+|---|---|---|
+| Codex Live | Existing Codex Provider row through `VendorOAuth.resolveAuth` | Renderer WebRTC, Main-process SDP negotiation |
+| Gemini Live | Google Generative AI API-key Provider | Main WebSocket and renderer PCM port |
+| OpenAI Realtime | API-key Provider with a configured endpoint | Main WebSocket and renderer PCM port; GA and compat-v1 are separate profiles |
+
+The public settings value is `liveVoice: { enabled, selectedBindingId?,
+bindings }`. It contains provider IDs, model/voice choices and protocol
+profile only; it never stores credentials. Existing `voice` and `speech`
+settings retain their prior meaning. Host Core owns the persisted settings
+JSON and merges the Live value with unrelated settings.
+
+Live Voice does not create an Agent turn, call AgentHost or MCP, access
+workspace files, execute model-generated functions, store recordings, or
+persist transcripts. Transcripts stay in a bounded renderer memory buffer for
+the current call. Provider delegation/function-call requests have no execution
+bridge and are rejected or cause a protocol error.
+
+## Ownership and security
+
+Electron Main owns the one-call slot, selected account, credential resolution,
+provider invalidation, capture lease, cancellation, protocol adapters, network
+transport and terminal cleanup. Renderer owns user interaction, WebRTC/PCM
+media and transient transcript display. IPC derives ownership from the invoking
+trusted main frame; payloads cannot provide an owner identity. Live events are
+sent only to the frame that owns the call.
+
+OAuth tokens and API keys remain in Main. SDP, audio and transcript content are
+not logged. Main WebSocket endpoints are validated before connection and use
+the configured desktop network proxy. Unsupported proxy routes fail closed.
+The PCM port exists for one prepared call, has bounded frame sizes and credits,
+and carries no credentials.
+
+Live and Dictation share a Main-process microphone lease. Local mute gates
+capture before the IPC request; Main independently rejects muted or stale
+capture epochs. Ending, renderer loss, window hide/navigation/crash, system
+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.
+
+## Calls and media
+
+The call state is `preparing → acquiring-mic → negotiating/connecting →
+connected → closing → ended|failed`. A request ID makes prepare idempotent and
+allows cancellation before a call ID arrives. Every startup, handshake,
+heartbeat, interruption acknowledgement and release wait is bounded. There is
+one active call per desktop instance; a later call is an explicit user action,
+with no automatic provider, model or billing fallback.
+
+Codex Live uses its dedicated Codex OAuth endpoint and WebRTC answer exchange;
+its browser data channel only handles normalized protocol events and the
+unsupported-delegation response. It does not use public GPT-Live session
+events. Gemini Live waits for `setupComplete` before sending 16 kHz mono
+PCM16. Realtime waits for `session.updated`, sends 24 kHz mono PCM16, and
+selects an explicit GA or compat-v1 wire profile. The supported models and
+voices are editable per binding; defaults are candidates, not claims of
+account access or service availability.
+
+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.
+
+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
+media behavior; Gemini interruption resets its local output queue; Realtime
+uses the played cursor to cancel and truncate its current response. Ending
+stops all local tracks, playback and ports before releasing the lease.
+
+## Settings and compatibility
+
+The Voice settings page lets the user bind an existing compatible Provider,
+choose the next-call binding, and set model, voice and Realtime profile. A
+currently active binding cannot be rewritten while its call is running. Turning
+Live Voice off ends the call. Provider credentials stay in the existing
+Provider/secret or VendorOAuth systems. Old settings with no `liveVoice` value
+read as disabled with no bindings; Dictation settings are preserved on every
+write and read.
+
+Live DTOs and IPC contracts live in `packages/shared`. Pure wire parsing and
+PCM math are exported only from `@pi-desktop/voice-runtime/live`; they do not
+enter the old local transcription runtime. Electron Main remains an
+orchestrator and does not transfer credential or storage ownership.
+
+## Verification and limits
+
+Automated coverage exercises PCM encoding/resampling, provider message
+parsing, owner checks, prepare/connect/mute/end, request cancellation,
+active-binding write protection, transcript bounds, reject-only delegation,
+and mutual exclusion with Dictation. Desktop UI tests and targeted Electron
+process tests cover the user path when available. A green fixture suite does
+not certify real provider access or account entitlement.
+
+Codex endpoint/model/voice details follow the referenced Piwin snapshot and
+are not a public API stability promise. Gemini and OpenAI Realtime require a
+compatible model, account and endpoint. Real-account calls, microphone
+permission prompts and hardware playback must be reported separately from
+automated fixture results; they may incur provider usage and require explicit
+user authorization.
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index d81b99fbb..5be7f4f3e 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -8,6 +8,31 @@
## 1. Goals
+### E2E-LIVE-VOICE-provider-call-lifecycle
+
+- **Preconditions:** Isolated desktop profile with Live Voice enabled and one
+ fixture provider binding. Use a deterministic local protocol fixture; do not
+ use a real provider account or paid endpoint for automation.
+- **Steps:** Open Voice settings, bind/select a fixture account for each
+ supported adapter profile, then open the Composer Live controls. Start,
+ cancel during permission/startup, connect, mute/unmute, interrupt playback,
+ inspect in-memory transcript, and end. Repeat with Dictation already holding
+ the microphone, a changed active binding, a provider credential removal,
+ renderer hide/reload, and a rejected playback gesture.
+- **Expected:** Live is off by default; old Dictation settings keep their
+ values; only the selected Provider ID is used; secrets do not enter Renderer;
+ no Agent, MCP, shell or file action runs; mute gates new input immediately;
+ cancellation stops late media; the transcript is not persisted; every end
+ path releases media and background-throttling leases or quarantines an
+ unconfirmed microphone lease. A new call starts only after explicit user
+ action.
+- **Specs:** [03-runtime/live-voice.md](../03-runtime/live-voice.md),
+ [03-runtime/20-speech.md](../03-runtime/20-speech.md).
+- **Acceptance:** Adapter setup and event parsing are local fixtures; Main
+ lifecycle, owner, lease and settings behavior are covered by targeted tests.
+ The full Electron flow and real-provider/device compatibility remain
+ unverified until their respective isolated acceptance environments are run.
+
### E2E-CHAT-fork-completed-reply-while-running
- **Preconditions:** Isolated real desktop profile, configured model, two turns
diff --git a/docs/spec/NAV.md b/docs/spec/NAV.md
index d524b15a2..269a87980 100644
--- a/docs/spec/NAV.md
+++ b/docs/spec/NAV.md
@@ -42,6 +42,7 @@
- [18-line-anchored-edit-contract.md](03-runtime/18-line-anchored-edit-contract.md)
- [19-remote-agent-control-protocol.md](03-runtime/19-remote-agent-control-protocol.md)
- [20-speech.md](03-runtime/20-speech.md)
+- [live-voice.md](03-runtime/live-voice.md)
- [21-image-generation.md](03-runtime/21-image-generation.md)
- [22-config-sync.md](03-runtime/22-config-sync.md)
- [svg-attachment-input.md](03-runtime/svg-attachment-input.md)
diff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
index 2181b99e0..59673d326 100644
--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md
@@ -38,6 +38,7 @@
| `menu` | 列入许可名单的应用程序菜单命令和本机 editing/window 操作 |
| `notification` | 持久收件箱 list/read/clear 和 new/activated 事件 |
| `stats` | 已完成回合的 token 历史(host RPC;仪表板由插件拥有) |
+| `voice/live` | 应用管理的实时语音通话、无凭证状态/设置 DTO 与每通电话专用媒体端口 |
## 3. 通道约定
@@ -1863,3 +1864,26 @@ unchanged. See [provider configuration](12-provider-config-schema.md).
输入密码只会被传给需要它的操作。原始秘密、vault key、解密资源或远端 archive 不会返回到 Renderer。`configSync.changed` 事件携带相同的脱敏状态,并由 Host 发起的变更(包括 Host scheduler)触发。Main 只是传输/生命周期协调器,不负责调度、合并、加密或应用配置。
手动同步会在运行期间报告 `configSync.progress`:当前阶段(`capture`、`download`、`merge`、`upload`、`apply` 或 `cleanup`)、该阶段已完成与总量,以及已知时的字节数。因此上传大量资源对象时,界面不会无内容可显示。后台轮询不报告进度,因为只有手动路径有调用方在等待。
+
+## 16. 实时语音 API
+
+实时语音是仅供主窗口使用、由应用管理的通话通路,详见[live-voice.md](live-voice.md)。DTO 定义在 `packages/shared/src/types/live-voice.ts`;preload 只暴露下表列出的白名单通道。Main 从调用 IPC 的受信 frame 推导 owner,并只向该 frame 发送通话事件。payload 不能提供 owner 身份或凭证。
+
+| IPC 通道 | 方向 | 契约 |
+|---|---|---|
+| `pi-desktop/voice/live/status` | Renderer → Main | 脱敏功能状态、绑定就绪情况和设置版本 |
+| `pi-desktop/voice/live/prepare` | Renderer → Main | 按 request ID 幂等准备通话;同步保留共享麦克风租约 |
+| `pi-desktop/voice/live/connect` | Renderer → Main | 连接已准备的通话;Codex 可附带有界 SDP offer |
+| `pi-desktop/voice/live/setMuted` | Renderer → Main | 通过单调递增的 capture epoch 设置静音 |
+| `pi-desktop/voice/live/reportMedia` | Renderer → Main | 报告采集、连接和释放生命周期;只有确认释放后才能复用租约 |
+| `pi-desktop/voice/live/reportPlayback` | Renderer → Main | 有界的 PCM 已播放游标列表,供中断/截断使用 |
+| `pi-desktop/voice/live/reportDelegation` | Renderer → Main | 报告 Provider 请求的 delegation;v1 会拒绝执行,也不会转发给 Agent/MCP |
+| `pi-desktop/voice/live/reportControlApplied` | Renderer → Main | 确认受支持的 Provider 控制,或报告拒绝了不支持的操作 |
+| `pi-desktop/voice/live/end` | Renderer → Main | 幂等结束活动通话,或取消等待中的请求 |
+| `pi-desktop/voice/live/heartbeat` | Renderer → Main | Renderer 正常响应时维持 owner 通话 |
+| `pi-desktop/voice/live/event/changed` | Main → Renderer | 脱敏通话阶段、错误、提示和活动状态 |
+| `pi-desktop/voice/live/event/port` | Main → Renderer | 转交一个通话专用 `MessagePort`,附带 call ID 和一次性 nonce |
+| `pi-desktop/voice/live/event/control` | Main → Renderer | Provider 控制请求,仅包含 v1 明确允许的控制类型 |
+| `pi-desktop/voice/live/event/transcript` | Main → Renderer | 当前通话的临时、有界字幕事件 |
+
+只有 owner 验证成功后才会创建 `MessagePort`,之后由 preload 中继到 renderer 窗口。owner 在首个 `hello` 中回送每通电话独有的 nonce;Main 仅在 call ID 和 nonce 均匹配时接受该端口一次。二进制帧包含有界 PCM 音频、采集 epoch、释放确认、播放游标和协议就绪信号。它不是通用 IPC 隧道:不会传输 Provider 凭证、任意命令、工作区路径、Agent 消息或持久化字幕。通话结束或 owner 丢失时会关闭端口。
diff --git a/docs/zh-CN/spec/03-runtime/08-error-codes.md b/docs/zh-CN/spec/03-runtime/08-error-codes.md
index 03b5864e0..152194d49 100644
--- a/docs/zh-CN/spec/03-runtime/08-error-codes.md
+++ b/docs/zh-CN/spec/03-runtime/08-error-codes.md
@@ -305,6 +305,39 @@ ADR 0285)。渲染进程除了一个标识徽章外看不到本地/远程之
| `PAIRING_TOKEN_EXPIRED` | 否 | 一次性配对令牌在配对完成前已过期 |
| `CAPABILITY_UNAVAILABLE` | 否 | 请求的操作对应主机声明为不可用的能力(如附件、工具中继) |
+### 3.9 实时语音
+
+实时语音错误通过应用所有的 IPC 和 Provider adapter 事件返回,不表示 Agent turn 失败。可重试错误表示瞬时条件清除后,用户可以重试同一通话;不会自动切换 Provider 或计费路径。
+
+| 代码 | 可重试 | 含义 |
+|---|---|---|
+| `LIVE_DISABLED` | 否 | 设置中关闭了实时语音 |
+| `LIVE_NOT_CONFIGURED` | 否 | 未选择有效的实时语音绑定 |
+| `LIVE_PROVIDER_NOT_FOUND` | 否 | 所选 Provider 不存在、已停用或解析凭证期间发生变化 |
+| `LIVE_AUTH_KIND_UNSUPPORTED` | 否 | 所选 Provider 凭证类型与 adapter 不兼容 |
+| `LIVE_AUTH_REQUIRED` | 否 | 缺少所需 OAuth/API key,或凭证被拒绝 |
+| `LIVE_ACCOUNT_ID_MISSING` | 否 | Codex OAuth 账号身份缺失或不一致 |
+| `LIVE_ACCESS_DENIED` | 否 | Provider 拒绝访问或账号无权限 |
+| `LIVE_RATE_LIMITED` | 是 | Provider 返回了速率限制响应 |
+| `LIVE_PROTOCOL_UNSUPPORTED` | 否 | endpoint、模型或所选协议 profile 不受支持 |
+| `LIVE_PROTOCOL_ERROR` | 否 | Provider 或 IPC 消息格式错误,或违反所选协议 |
+| `LIVE_ALREADY_ACTIVE` | 否 | 另一通实时语音通话或麦克风释放隔离占用唯一通话槽位 |
+| `LIVE_REQUEST_CONFLICT` | 否 | 相同幂等 request ID 被不同通话参数重复使用 |
+| `LIVE_SETTINGS_IN_USE` | 否 | 准备期间设置发生变化,或活动绑定不可编辑 |
+| `LIVE_MEDIA_RELEASE_UNCONFIRMED` | 否 | 未收到 Renderer 的媒体释放确认;Main 隔离麦克风租约 |
+| `LIVE_STALE_CALL` | 否 | 通话、请求或采集 epoch 已不是当前值 |
+| `LIVE_INVALID_OWNER` | 否 | IPC 或媒体端口 owner 与受信主 frame 不匹配 |
+| `LIVE_MICROPHONE_BUSY` | 否 | Dictation、另一通 Live 通话或尚未确认的释放占用共享采集租约 |
+| `LIVE_MICROPHONE_DENIED` | 否 | 用户或操作系统拒绝麦克风权限 |
+| `LIVE_MICROPHONE_UNAVAILABLE` | 否 | 没有可用的麦克风设备 |
+| `LIVE_MEDIA_UNSUPPORTED` | 否 | 浏览器媒体或 AudioWorklet 支持不可用 |
+| `LIVE_PLAYBACK_BLOCKED` | 不确定 | 浏览器播放需要用户手势才能开始或恢复 |
+| `LIVE_TIMEOUT` | 是 | 有时限的启动、握手、heartbeat、控制或清理阶段超时 |
+| `LIVE_NETWORK_ERROR` | 是 | Provider 传输发生暂时性连接故障 |
+| `LIVE_NETWORK_POLICY_UNSUPPORTED` | 否 | 桌面代理路由无法由 Live 传输安全表示 |
+| `LIVE_AUDIO_BACKPRESSURE` | 否 | PCM 或播放 credit 的有界容量已耗尽 |
+| `LIVE_EXECUTION_NOT_CONNECTED` | 否 | Provider 请求了当前不支持的函数/delegation 执行路径 |
+
## 4. 映射规则
### 主机 RPC 数字 → AppError.code
diff --git a/docs/zh-CN/spec/03-runtime/README.md b/docs/zh-CN/spec/03-runtime/README.md
index 42e009c29..15693e8d1 100644
--- a/docs/zh-CN/spec/03-runtime/README.md
+++ b/docs/zh-CN/spec/03-runtime/README.md
@@ -25,5 +25,6 @@
| [18-line-anchored-edit-contract.md](/zh-CN/spec/03-runtime/18-line-anchored-edit-contract) | 按行锚定的 Edit 合约 |
| [19-remote-agent-control-protocol.md](/zh-CN/spec/03-runtime/19-remote-agent-control-protocol) | 远程 Agent 控制协议 |
| [20-speech.md](/zh-CN/spec/03-runtime/20-speech) | 宿主语音(转写/朗读) |
+| [live-voice.md](/zh-CN/spec/03-runtime/live-voice) | 应用托管的实时语音通话 |
- [图片生成与编辑](/zh-CN/spec/03-runtime/21-image-generation)
diff --git a/docs/zh-CN/spec/03-runtime/live-voice.md b/docs/zh-CN/spec/03-runtime/live-voice.md
new file mode 100644
index 000000000..8706b24d4
--- /dev/null
+++ b/docs/zh-CN/spec/03-runtime/live-voice.md
@@ -0,0 +1,47 @@
+# 实时语音 v1
+
+> **翻译说明:** 本页与[英文源规格](/spec/03-runtime/live-voice)对应。代码、协议字段和标识符保留原文;如翻译与英文事实存在差异,以英文版本为准。
+
+## 范围
+
+实时语音是可选、由应用管理的实时音频通路,与本地听写和 Host Speech 分开,默认关闭。v1 支持三种明确绑定:
+
+| Adapter | 凭证所有者 | 传输方式 |
+|---|---|---|
+| Codex Live | 通过 `VendorOAuth.resolveAuth` 使用现有 Codex Provider 行 | Renderer WebRTC,由 Main 进程完成 SDP 协商 |
+| Gemini Live | Google Generative AI API Key Provider | Main WebSocket 与 Renderer PCM 端口 |
+| OpenAI Realtime | 配置了 endpoint 的 API Key Provider | Main WebSocket 与 Renderer PCM 端口;GA 和 compat-v1 使用独立 profile |
+
+公开设置为 `liveVoice: { enabled, selectedBindingId?, bindings }`。它只包含 Provider ID、模型/音色选择和协议 profile,不保存凭证。现有 `voice` 和 `speech` 设置保持原义。持久化 JSON 由 Host Core 所有;它会将 Live 设置与其他设置合并。
+
+实时语音不会创建 Agent turn、调用 AgentHost 或 MCP、访问工作区文件、执行模型生成的函数、保存录音或持久化字幕。字幕只保存在本次通话的有界 Renderer 内存缓冲区中。Provider delegation/function-call 请求没有执行通路,会被拒绝或导致协议错误。
+
+## 所有权与安全
+
+Electron Main 管理唯一通话槽位、所选账号、凭证解析、Provider 撤销、麦克风租约、取消、协议适配器、网络传输和终态清理。Renderer 管理用户交互、WebRTC/PCM 媒体和临时字幕显示。IPC 从调用它的受信主 frame 推导所有者,payload 不能自行声明 owner。Live 事件只发送给拥有通话的 frame。
+
+OAuth token 和 API key 留在 Main。SDP、音频和字幕内容不写入日志。Main 的 WebSocket endpoint 在连接前校验,并使用桌面网络代理配置;不支持的代理路由会被拒绝。PCM 端口仅属于一个已准备的通话,帧大小和 credit 都有上限,且不携带凭证。
+
+Live 与 Dictation 共用 Main 进程的麦克风租约。本地 mute 会在 IPC 请求前门控采集;Main 也会独立拒绝静音或过期的采集 epoch。通话结束、Renderer 丢失、窗口隐藏/导航/崩溃、系统挂起/锁定、Provider 变更、功能关闭或应用退出时,都会停止媒体并关闭 adapter。如果无法确认 Renderer 已释放媒体,Main 会隔离麦克风租约,不会盲目复用。
+
+## 通话与媒体
+
+通话状态为 `preparing → acquiring-mic → negotiating/connecting → connected → closing → ended|failed`。request ID 让 prepare 幂等,并可在 call ID 返回前取消。启动、握手、heartbeat、中断确认和释放等待均有时限。每个 Desktop 实例同时只能有一个通话;后续通话需要用户明确发起,不会自动切换 Provider、模型或计费路径。
+
+Codex Live 使用专用 Codex OAuth endpoint 和 WebRTC answer exchange;浏览器 data channel 只处理规范化协议事件和不支持 delegation 的响应。它不使用公共 GPT-Live session 事件。Gemini Live 在发送 16 kHz 单声道 PCM16 前会等待 `setupComplete`。Realtime 会等待 `session.updated`,使用 24 kHz 单声道 PCM16,并明确选择 GA 或 compat-v1 wire profile。用户可分别编辑每项绑定的模型和音色;默认值只是候选项,不代表账号有访问权限或服务可用。
+
+PCM 采集使用 AudioWorklet,依据实际 `AudioContext.sampleRate` 进行有状态抗混叠重采样,并产生有界的 20 ms worklet 帧。PCM 输出由独立播放通路排队,记录每个 item 实际播放位置;中断会推进 playback epoch 并丢弃过期队列。如果浏览器阻止播放,通话面板会提供用户手势来恢复声音。输入音频不会回环到本地扬声器。
+
+静音、插话和结束是不同操作。静音只门控新的输入,Provider 输出仍可播放。Codex 使用其原生全双工媒体行为;Gemini 中断时重置本地输出队列;Realtime 根据实际播放游标取消并截断当前响应。结束通话时,先停止本地 tracks、播放和端口,再释放租约。
+
+## 设置与兼容性
+
+Voice 设置页允许绑定现有兼容 Provider、选择下次通话使用的绑定,以及设置模型、音色和 Realtime profile。通话进行中,当前绑定不可修改。关闭实时语音会结束通话。Provider 凭证继续由现有 Provider/secret 或 VendorOAuth 系统管理。旧设置中没有 `liveVoice` 时,会按关闭且无绑定处理;Dictation 设置在每次读写中都会保留。
+
+Live DTO 与 IPC 合同位于 `packages/shared`。纯 wire 解析和 PCM 数学逻辑只从 `@pi-desktop/voice-runtime/live` 导出,不进入旧的本地转写运行时。Electron Main 保持编排角色,不接管凭证或存储所有权。
+
+## 验证与限制
+
+自动化覆盖 PCM 编码/重采样、Provider 消息解析、owner 检查、prepare/connect/mute/end、请求取消、活动绑定写保护、字幕上限、只拒绝 delegation 的行为,以及与 Dictation 的互斥。桌面 UI 测试和定向 Electron 进程测试在适用时覆盖用户路径。fixture 通过不能证明真实 Provider 访问权限或账号资格。
+
+Codex endpoint、模型和音色细节依据所引用的 Piwin 快照,不承诺公共 API 稳定性。Gemini 与 OpenAI Realtime 需要兼容模型、账号和 endpoint。真实账号调用、麦克风权限提示和硬件播放须与自动化 fixture 结果分开报告;它们可能产生 Provider 用量,并需要用户明确授权。
diff --git a/docs/zh-CN/spec/NAV.md b/docs/zh-CN/spec/NAV.md
index 86397e23d..b509a8365 100644
--- a/docs/zh-CN/spec/NAV.md
+++ b/docs/zh-CN/spec/NAV.md
@@ -45,6 +45,7 @@
- [18-line-anchored-edit-contract.md](/zh-CN/spec/03-runtime/18-line-anchored-edit-contract)
- [19-remote-agent-control-protocol.md](/zh-CN/spec/03-runtime/19-remote-agent-control-protocol)
- [20-speech.md](/zh-CN/spec/03-runtime/20-speech)
+- [live-voice.md](/zh-CN/spec/03-runtime/live-voice)
- [21-image-generation.md](/zh-CN/spec/03-runtime/21-image-generation)
- [22-config-sync.md](/zh-CN/spec/03-runtime/22-config-sync)
- [svg-attachment-input.md](/zh-CN/spec/03-runtime/svg-attachment-input)
diff --git a/packages/agent-runtime/package.json b/packages/agent-runtime/package.json
index c816b8a6d..a879e7b27 100644
--- a/packages/agent-runtime/package.json
+++ b/packages/agent-runtime/package.json
@@ -13,6 +13,10 @@
"./sidecar": {
"types": "./dist/sidecar.d.ts",
"import": "./dist/sidecar.js"
+ },
+ "./proxy-tunnel": {
+ "types": "./dist/socks5.d.ts",
+ "import": "./dist/socks5.js"
}
},
"scripts": {
diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.ts
index cb867c419..d74f31080 100644
--- a/packages/i18n/src/locales/de/index.ts
+++ b/packages/i18n/src/locales/de/index.ts
@@ -1,4 +1,4 @@
-import type { EnglishCatalog } from "../en/index.js";
+import { en, type EnglishCatalog } from "../en/index.js";
export const de = {
"app": {
@@ -2418,6 +2418,21 @@ sklm: {
"actionFailed": "Benachrichtigungen konnten nicht aktualisiert werden.",
"justNow": "Gerade eben"
},
+ liveVoice: {
+ ...en.liveVoice,
+ title: "Live-Sprache",
+ 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.",
+ 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" },
+ },
"errors": {
"HOST_UNAVAILABLE": "Der lokale Dienst ist nicht verfügbar",
"MODEL_NOT_CONFIGURED": "Dieses Modell ist nicht eingerichtet oder der KI-Anbieter bietet es nicht an.",
diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.ts
index bdaf1bc7d..45c06d9e8 100644
--- a/packages/i18n/src/locales/en/index.ts
+++ b/packages/i18n/src/locales/en/index.ts
@@ -2459,6 +2459,67 @@ importConfirm: "Imported extensions run inside the agent process with the same a
actionFailed: "Couldn't update notifications.",
justNow: "Just now",
},
+ liveVoice: {
+ title: "Live voice",
+ 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.",
+ bindingStatus: "Provider status",
+ ready: "Ready",
+ provider: "Provider account",
+ chooseProvider: "Choose a provider account",
+ providerUnavailable: "Selected provider is unavailable",
+ providerDisabled: "disabled",
+ credentialsMissing: "credentials missing",
+ model: "Model ID",
+ voice: "Voice",
+ profile: "Protocol profile",
+ profiles: { "realtime-ga": "OpenAI Realtime GA", "realtime-compat-v1": "Realtime compat v1" },
+ useForNextCall: "Use for the next call",
+ bindingLocked: "Call in progress",
+ bindingLockedDetail: "End the call to apply changes to this provider binding.",
+ saveFailed: "Couldn't save Live voice settings.",
+ adapters: {
+ "codex-live": { title: "Codex account", description: "Uses the selected Codex account and its existing sign-in." },
+ "gemini-live": { title: "Gemini Live", description: "Uses a Google Generative AI provider with an API key." },
+ "openai-realtime": { title: "OpenAI Realtime compatible", description: "Uses an API-key provider with an explicit Realtime protocol profile." },
+ },
+ readiness: {
+ disabled: "Provider disabled",
+ "missing-provider": "Provider unavailable",
+ "missing-credentials": "Credentials missing",
+ "wrong-auth-kind": "Unsupported authentication",
+ "unsupported-adapter": "Unsupported adapter",
+ "invalid-settings": "Invalid settings",
+ },
+ openPanel: "Open Live voice controls",
+ start: "Start Live voice",
+ end: "End call",
+ mute: "Mute microphone",
+ unmute: "Unmute microphone",
+ resumePlayback: "Enable 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.",
+ microphoneBusy: "The microphone is in use by another recording. Stop it before starting Live voice.",
+ userSpeaking: "Listening",
+ assistantSpeaking: "Speaking",
+ muted: "Microphone muted",
+ noProvider: "Choose a supported provider in Settings → Voice.",
+ enableInSettings: "Enable Live voice in Settings → Voice.",
+ phase: {
+ idle: "Off",
+ preparing: "Preparing",
+ "acquiring-mic": "Waiting for microphone",
+ negotiating: "Negotiating",
+ connecting: "Connecting",
+ connected: "Connected",
+ reconnecting: "Reconnecting",
+ closing: "Ending",
+ ended: "Ended",
+ failed: "Stopped",
+ },
+ },
errors: {
HOST_UNAVAILABLE: "The local service is unavailable",
MODEL_NOT_CONFIGURED: "This model isn't set up, or the AI provider doesn't offer it.",
diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.ts
index 7d9acfe17..28bc969a4 100644
--- a/packages/i18n/src/locales/es/index.ts
+++ b/packages/i18n/src/locales/es/index.ts
@@ -1,4 +1,4 @@
-import type { EnglishCatalog } from "../en/index.js";
+import { en, type EnglishCatalog } from "../en/index.js";
export const es = {
"app": {
@@ -2418,6 +2418,16 @@ sklm: {
"actionFailed": "No se pudieron actualizar las notificaciones.",
"justNow": "Justo ahora"
},
+ liveVoice: {
+ ...en.liveVoice,
+ 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.",
+ 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.",
+ 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" },
+ },
"errors": {
"HOST_UNAVAILABLE": "El servicio local no está disponible",
"MODEL_NOT_CONFIGURED": "Este modelo no está configurado o el proveedor de IA no lo ofrece.",
diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.ts
index 724e751a3..b40d26105 100644
--- a/packages/i18n/src/locales/fr/index.ts
+++ b/packages/i18n/src/locales/fr/index.ts
@@ -1,4 +1,4 @@
-import type { EnglishCatalog } from "../en/index.js";
+import { en, type EnglishCatalog } from "../en/index.js";
export const fr = {
"app": {
@@ -2418,6 +2418,16 @@ sklm: {
"actionFailed": "Impossible de mettre à jour les notifications.",
"justNow": "À l'instant"
},
+ liveVoice: {
+ ...en.liveVoice,
+ 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.",
+ 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é.",
+ 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" },
+ },
"errors": {
"HOST_UNAVAILABLE": "Le service local n'est pas disponible",
"MODEL_NOT_CONFIGURED": "Ce modèle n'est pas configuré ou le fournisseur d'IA ne le propose pas.",
diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.ts
index f4d96e985..5a72f60e7 100644
--- a/packages/i18n/src/locales/ko/index.ts
+++ b/packages/i18n/src/locales/ko/index.ts
@@ -1,4 +1,4 @@
-import type { EnglishCatalog } from "../en/index.js";
+import { en, type EnglishCatalog } from "../en/index.js";
export const ko = {
app: {
@@ -2454,6 +2454,16 @@ importConfirm: "가져온 확장은 에이전트 프로세스 안에서 에이
actionFailed: "알림을 업데이트할 수 없습니다.",
justNow: "방금",
},
+ liveVoice: {
+ ...en.liveVoice,
+ title: "실시간 음성", description: "설정된 실시간 음성 제공자와 직접 대화합니다. 활성화하기 전까지 꺼져 있습니다.",
+ enable: "실시간 음성 사용", enableDetail: "마이크 오디오가 선택한 제공자에게 전송됩니다. 에이전트, 도구 또는 MCP 작업은 실행되지 않습니다.",
+ 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: "중지됨" },
+ },
errors: {
HOST_UNAVAILABLE: "로컬 서비스를 사용할 수 없습니다",
MODEL_NOT_CONFIGURED: "이 모델이 설정되지 않았거나 AI 프로바이더에서 제공하지 않습니다.",
diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.ts
index 452502bb8..86ffc8ff7 100644
--- a/packages/i18n/src/locales/pt-BR/index.ts
+++ b/packages/i18n/src/locales/pt-BR/index.ts
@@ -1,4 +1,4 @@
-import type { EnglishCatalog } from "../en/index.js";
+import { en, type EnglishCatalog } from "../en/index.js";
export const ptBR = {
app: {
@@ -2373,6 +2373,16 @@ export const ptBR = {
actionFailed: "Não foi possível atualizar as notificações.",
justNow: "Agora mesmo",
},
+ liveVoice: {
+ ...en.liveVoice,
+ 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.",
+ 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.",
+ 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" },
+ },
errors: {
HOST_UNAVAILABLE: "O serviço local está indisponível",
MODEL_NOT_CONFIGURED: "Este modelo não está configurado ou o provedor de IA não o oferece.",
diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.ts
index 35f54ab25..36b8d0d4c 100644
--- a/packages/i18n/src/locales/tr/index.ts
+++ b/packages/i18n/src/locales/tr/index.ts
@@ -1,4 +1,4 @@
-import type { EnglishCatalog } from "../en/index.js";
+import { en, type EnglishCatalog } from "../en/index.js";
export const tr = {
app: {
@@ -2444,6 +2444,16 @@ importConfirm: "İçe aktarılan uzantılar ajan sürecinde, ajanın kendi araç
actionFailed: "Bildirimler güncellenemedi.",
justNow: "Az önce",
},
+ liveVoice: {
+ ...en.liveVoice,
+ 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.",
+ 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.",
+ 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" },
+ },
errors: {
HOST_UNAVAILABLE: "Yerel servis kullanılamıyor",
MODEL_NOT_CONFIGURED: "Bu model kurulu değil veya AI servisi onu sunmuyor.",
diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.ts
index ec16c49a1..2573e4233 100644
--- a/packages/i18n/src/locales/zh-CN/index.ts
+++ b/packages/i18n/src/locales/zh-CN/index.ts
@@ -1,4 +1,4 @@
-import type { EnglishCatalog } from "../en/index.js";
+import { en, type EnglishCatalog } from "../en/index.js";
export const zhCN = {
app: {
@@ -2407,6 +2407,47 @@ sklm: {
actionFailed: "无法更新通知。",
justNow: "刚刚",
},
+ liveVoice: {
+ ...en.liveVoice,
+ title: "实时语音",
+ description: "直接与已配置的实时语音服务交谈。启用前,实时语音处于关闭状态。",
+ enable: "启用实时语音",
+ enableDetail: "麦克风音频会发送给你选择的服务。此功能不会运行 Agent、工具或 MCP 操作。",
+ bindingStatus: "服务状态",
+ ready: "就绪",
+ provider: "服务账号",
+ chooseProvider: "选择服务账号",
+ providerUnavailable: "所选服务不可用",
+ providerDisabled: "已停用",
+ credentialsMissing: "缺少凭证",
+ model: "模型 ID",
+ voice: "音色",
+ profile: "协议配置",
+ profiles: { "realtime-ga": "OpenAI Realtime GA", "realtime-compat-v1": "Realtime 兼容版 v1" },
+ 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: "实时语音已停止。请检查服务配置后重试。",
+ microphoneDenied: "请在浏览器和系统设置中允许麦克风访问,然后重试。",
+ microphoneUnavailable: "找不到可用的麦克风。请检查所选设备及其连接。",
+ microphoneBusy: "麦克风正被其他录音占用。请先停止录音,再启动实时语音。",
+ noProvider: "请在 设置 → 语音 中选择受支持的服务。",
+ enableInSettings: "请在 设置 → 语音 中启用实时语音。",
+ phase: { idle: "关闭", preparing: "正在准备", "acquiring-mic": "等待麦克风", negotiating: "正在协商", connecting: "正在连接", connected: "已连接", reconnecting: "正在重连", closing: "正在结束", ended: "已结束", failed: "已停止" },
+ },
errors: {
HOST_UNAVAILABLE: "本地服务不可用",
MODEL_NOT_CONFIGURED: "该模型尚未配置,或当前 AI 服务不提供此模型。",
diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.ts
index b3b055ddb..e8db71c92 100644
--- a/packages/i18n/src/locales/zh-TW/index.ts
+++ b/packages/i18n/src/locales/zh-TW/index.ts
@@ -1,4 +1,4 @@
-import type { EnglishCatalog } from "../en/index.js";
+import { en, type EnglishCatalog } from "../en/index.js";
export const zhTW = {
app: {
@@ -2405,6 +2405,44 @@ sklm: {
actionFailed: "無法更新通知。",
justNow: "剛剛",
},
+ liveVoice: {
+ ...en.liveVoice,
+ title: "即時語音",
+ description: "直接與已設定的即時語音服務交談。啟用前,即時語音會保持關閉。",
+ enable: "啟用即時語音",
+ enableDetail: "麥克風音訊會傳送給你選擇的服務。此功能不會執行 Agent、工具或 MCP 操作。",
+ bindingStatus: "服務狀態",
+ ready: "就緒",
+ provider: "服務帳戶",
+ chooseProvider: "選擇服務帳戶",
+ providerUnavailable: "所選服務無法使用",
+ providerDisabled: "已停用",
+ credentialsMissing: "缺少憑證",
+ model: "模型 ID",
+ voice: "音色",
+ profile: "協定設定檔",
+ profiles: { "realtime-ga": "OpenAI Realtime GA", "realtime-compat-v1": "Realtime 相容版 v1" },
+ 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: "已停止" },
+ },
errors: {
HOST_UNAVAILABLE: "本地服務不可用",
MODEL_NOT_CONFIGURED: "該模型尚未配置,或當前 AI 服務不提供此模型。",
diff --git a/packages/shared/src/errors.ts b/packages/shared/src/errors.ts
index 271545863..1b60ce489 100644
--- a/packages/shared/src/errors.ts
+++ b/packages/shared/src/errors.ts
@@ -65,6 +65,32 @@ export const ErrorCodes = {
* same request succeed.
*/
NETWORK_RESOLVE_FAILED: "NETWORK_RESOLVE_FAILED",
+ LIVE_DISABLED: "LIVE_DISABLED",
+ LIVE_NOT_CONFIGURED: "LIVE_NOT_CONFIGURED",
+ LIVE_PROVIDER_NOT_FOUND: "LIVE_PROVIDER_NOT_FOUND",
+ LIVE_AUTH_KIND_UNSUPPORTED: "LIVE_AUTH_KIND_UNSUPPORTED",
+ LIVE_AUTH_REQUIRED: "LIVE_AUTH_REQUIRED",
+ LIVE_ACCOUNT_ID_MISSING: "LIVE_ACCOUNT_ID_MISSING",
+ LIVE_ACCESS_DENIED: "LIVE_ACCESS_DENIED",
+ LIVE_RATE_LIMITED: "LIVE_RATE_LIMITED",
+ LIVE_PROTOCOL_UNSUPPORTED: "LIVE_PROTOCOL_UNSUPPORTED",
+ LIVE_PROTOCOL_ERROR: "LIVE_PROTOCOL_ERROR",
+ LIVE_ALREADY_ACTIVE: "LIVE_ALREADY_ACTIVE",
+ LIVE_REQUEST_CONFLICT: "LIVE_REQUEST_CONFLICT",
+ LIVE_SETTINGS_IN_USE: "LIVE_SETTINGS_IN_USE",
+ LIVE_MEDIA_RELEASE_UNCONFIRMED: "LIVE_MEDIA_RELEASE_UNCONFIRMED",
+ LIVE_STALE_CALL: "LIVE_STALE_CALL",
+ LIVE_INVALID_OWNER: "LIVE_INVALID_OWNER",
+ LIVE_MICROPHONE_BUSY: "LIVE_MICROPHONE_BUSY",
+ LIVE_MICROPHONE_DENIED: "LIVE_MICROPHONE_DENIED",
+ LIVE_MICROPHONE_UNAVAILABLE: "LIVE_MICROPHONE_UNAVAILABLE",
+ LIVE_MEDIA_UNSUPPORTED: "LIVE_MEDIA_UNSUPPORTED",
+ LIVE_PLAYBACK_BLOCKED: "LIVE_PLAYBACK_BLOCKED",
+ LIVE_TIMEOUT: "LIVE_TIMEOUT",
+ LIVE_NETWORK_ERROR: "LIVE_NETWORK_ERROR",
+ LIVE_NETWORK_POLICY_UNSUPPORTED: "LIVE_NETWORK_POLICY_UNSUPPORTED",
+ LIVE_AUDIO_BACKPRESSURE: "LIVE_AUDIO_BACKPRESSURE",
+ LIVE_EXECUTION_NOT_CONNECTED: "LIVE_EXECUTION_NOT_CONNECTED",
AGENT_BUSY: "AGENT_BUSY",
AGENT_NOT_FOUND: "AGENT_NOT_FOUND",
TURN_NOT_FOUND: "TURN_NOT_FOUND",
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index e016c2c92..4e07b8ad6 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -91,6 +91,16 @@ export const IPC = {
voiceUpdateSettings: "pi-desktop/voice/updateSettings",
voiceCheckPermission: "pi-desktop/voice/checkPermission",
voiceRequestPermission: "pi-desktop/voice/requestPermission",
+ liveVoiceStatus: "pi-desktop/voice/live/status",
+ liveVoicePrepare: "pi-desktop/voice/live/prepare",
+ liveVoiceConnect: "pi-desktop/voice/live/connect",
+ liveVoiceSetMuted: "pi-desktop/voice/live/setMuted",
+ liveVoiceReportMedia: "pi-desktop/voice/live/reportMedia",
+ liveVoiceReportPlayback: "pi-desktop/voice/live/reportPlayback",
+ liveVoiceReportDelegation: "pi-desktop/voice/live/reportDelegation",
+ liveVoiceReportControlApplied: "pi-desktop/voice/live/reportControlApplied",
+ liveVoiceEnd: "pi-desktop/voice/live/end",
+ liveVoiceHeartbeat: "pi-desktop/voice/live/heartbeat",
agentCompact: "pi-desktop/agent/compact",
agentAbort: "pi-desktop/agent/abort",
agentStop: "pi-desktop/agent/stop",
@@ -386,6 +396,10 @@ export const IPC = {
updatesState: "pi-desktop/updates/event/state",
voiceStateChanged: "pi-desktop/voice/event/stateChanged",
voiceModelProgress: "pi-desktop/voice/event/modelProgress",
+ liveVoiceChanged: "pi-desktop/voice/live/event/changed",
+ liveVoicePort: "pi-desktop/voice/live/event/port",
+ liveVoiceControl: "pi-desktop/voice/live/event/control",
+ liveVoiceTranscript: "pi-desktop/voice/live/event/transcript",
},
} as const;
diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.ts
index 402047cd7..0efa0db0d 100644
--- a/packages/shared/src/types.ts
+++ b/packages/shared/src/types.ts
@@ -23,3 +23,4 @@ export * from "./types/filesystem.js";
export * from "./types/speech.js";
export * from "./types/remote-host.js";
export * from "./types/config-sync.js";
+export * from "./types/live-voice.js";
diff --git a/packages/shared/src/types/live-voice.ts b/packages/shared/src/types/live-voice.ts
new file mode 100644
index 000000000..42b68e876
--- /dev/null
+++ b/packages/shared/src/types/live-voice.ts
@@ -0,0 +1,244 @@
+/** Public, secret-free contracts for the app-owned real-time voice feature. */
+
+export const LIVE_ADAPTER_IDS = [
+ "codex-live",
+ "gemini-live",
+ "openai-realtime",
+] as const;
+
+export type LiveAdapterId = (typeof LIVE_ADAPTER_IDS)[number];
+export type LiveRealtimeWireProfile = "realtime-ga" | "realtime-compat-v1";
+
+export type LiveBinding =
+ | {
+ id: string;
+ adapterId: "codex-live";
+ providerId: string;
+ voice: string;
+ }
+ | {
+ id: string;
+ adapterId: "gemini-live";
+ providerId: string;
+ modelId: string;
+ voice: string;
+ }
+ | {
+ id: string;
+ adapterId: "openai-realtime";
+ providerId: string;
+ modelId: string;
+ voice: string;
+ wireProfile: LiveRealtimeWireProfile;
+ };
+
+export type LiveVoiceSettings = {
+ enabled: boolean;
+ selectedBindingId?: string;
+ bindings: LiveBinding[];
+};
+
+export function validateLiveVoiceSettings(value: unknown): LiveVoiceSettings {
+ const invalid = (): never => {
+ throw Object.assign(new Error("liveVoice settings are invalid"), {
+ errorCode: "INVALID_PARAMS",
+ });
+ };
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();
+ const input = value as Record<string, unknown>;
+ if (Object.keys(input).some((key) => !["enabled", "selectedBindingId", "bindings"].includes(key))) return invalid();
+ if (typeof input.enabled !== "boolean" || !Array.isArray(input.bindings) || input.bindings.length > 12) return invalid();
+
+ const cleanId = (item: unknown, maxLength = 256): string => {
+ if (typeof item !== "string" || !item.trim() || item.trim() !== item || item.length > maxLength) return invalid();
+ return item;
+ };
+ const allowedKeys: Record<string, string[]> = {
+ "codex-live": ["id", "adapterId", "providerId", "voice"],
+ "gemini-live": ["id", "adapterId", "providerId", "modelId", "voice"],
+ "openai-realtime": ["id", "adapterId", "providerId", "modelId", "voice", "wireProfile"],
+ };
+ const bindings: LiveBinding[] = input.bindings.map((raw) => {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return invalid();
+ const item = raw as Record<string, unknown>;
+ if (typeof item.adapterId !== "string" || !Object.hasOwn(allowedKeys, item.adapterId)) return invalid();
+ if (Object.keys(item).some((key) => !allowedKeys[item.adapterId as string].includes(key))) return invalid();
+ const id = cleanId(item.id);
+ const providerId = cleanId(item.providerId);
+ const voice = cleanId(item.voice, 64);
+ if (item.adapterId === "codex-live") return { id, adapterId: "codex-live", providerId, voice };
+ const modelId = cleanId(item.modelId);
+ if (item.adapterId === "gemini-live") return { id, adapterId: "gemini-live", providerId, modelId, voice };
+ if (item.wireProfile !== "realtime-ga" && item.wireProfile !== "realtime-compat-v1") return invalid();
+ return { id, adapterId: "openai-realtime", providerId, modelId, voice, wireProfile: item.wireProfile };
+ });
+ const ids = new Set<string>();
+ for (const binding of bindings) {
+ if (ids.has(binding.id)) return invalid();
+ ids.add(binding.id);
+ }
+ let selectedBindingId: string | undefined;
+ if (input.selectedBindingId !== undefined) {
+ selectedBindingId = cleanId(input.selectedBindingId);
+ if (!ids.has(selectedBindingId)) return invalid();
+ }
+ return {
+ enabled: input.enabled,
+ ...(selectedBindingId ? { selectedBindingId } : {}),
+ bindings,
+ };
+}
+
+export type LivePhase =
+ | "idle"
+ | "preparing"
+ | "acquiring-mic"
+ | "negotiating"
+ | "connecting"
+ | "connected"
+ | "reconnecting"
+ | "closing"
+ | "ended"
+ | "failed";
+
+export type LiveEndReason =
+ | "user-ended"
+ | "user-cancelled-start"
+ | "window-hidden"
+ | "window-navigated"
+ | "renderer-gone"
+ | "app-suspended"
+ | "app-quit"
+ | "provider-invalidated"
+ | "disabled"
+ | "timeout"
+ | "network-error"
+ | "protocol-error"
+ | "audio-backpressure"
+ | "media-release-unconfirmed";
+
+export type LiveError = {
+ code: string;
+ stage?: string;
+ retriable: boolean;
+};
+
+export type LiveTranscriptSegment = {
+ id: string;
+ role: "user" | "assistant" | "system";
+ text: string;
+ final: boolean;
+ timestamp: number;
+};
+
+export type LiveCallView = {
+ callId: string;
+ revision: number;
+ bindingId: string;
+ adapterId: LiveAdapterId;
+ phase: LivePhase;
+ muted: boolean;
+ microphoneActive: boolean;
+ userSpeaking: boolean;
+ assistantSpeaking: boolean;
+ connectedAt?: string;
+ playbackBlocked?: boolean;
+ mediaRelease?: "pending" | "confirmed" | "unconfirmed";
+ error?: LiveError;
+ notice?: LiveError;
+};
+
+export type LiveBindingReadiness = {
+ bindingId: string;
+ adapterId: LiveAdapterId;
+ configured: boolean;
+ credentialsPresent: boolean;
+ selectable: boolean;
+ reason?:
+ | "disabled"
+ | "missing-provider"
+ | "missing-credentials"
+ | "wrong-auth-kind"
+ | "unsupported-adapter"
+ | "invalid-settings";
+ providerLabel?: string;
+};
+
+export type LiveStatus = {
+ enabled: boolean;
+ settingsRevision: number;
+ selectedBindingId?: string;
+ bindings: LiveBindingReadiness[];
+ call: LiveCallView | null;
+};
+
+export type LivePrepareRequest = {
+ requestId: string;
+ bindingId: string;
+ expectedSettingsRevision: number;
+ initialMuted: boolean;
+};
+
+export type LivePreparedCall = {
+ callId: string;
+ requestId: string;
+ bindingId: string;
+ adapterId: LiveAdapterId;
+ inputSampleRate: 16000 | 24000;
+ outputSampleRate: 24000;
+ initialMuted: boolean;
+ revision: number;
+} & (
+ | { mediaKind: "webrtc" }
+ | { mediaKind: "pcm"; portNonce: string }
+);
+
+export type LiveConnectRequest = {
+ callId: string;
+ /** Present only for the Codex WebRTC adapter. */
+ offerSdp?: string;
+};
+
+export type LiveConnectResult = {
+ answerSdp?: string;
+ revision: number;
+};
+
+export type LiveMediaReport =
+ | { callId: string; kind: "microphone-active"; active: boolean }
+ | { callId: string; kind: "phase"; phase: "connecting" | "connected" }
+ | { callId: string; kind: "activity"; userSpeaking?: boolean; assistantSpeaking?: boolean }
+ | { callId: string; kind: "playback-blocked"; blocked: boolean }
+ | { callId: string; kind: "released" };
+
+export type LiveEndRequest =
+ | { callId: string; reason: LiveEndReason }
+ | { requestId: string; reason: "user-cancelled-start" };
+
+export type LiveDelegationRequest = {
+ callId: string;
+ delegationId: string;
+ instruction: string;
+};
+
+export type LivePortEvent = {
+ callId: string;
+ nonce: string;
+};
+
+export type LivePlaybackCursor = {
+ itemId: string;
+ contentIndex: number;
+ playedSamples: number;
+ sampleRate: 24000;
+};
+
+export type LiveControlEvent =
+ | { callId: string; kind: "release-media" }
+ | { callId: string; kind: "reject-delegation"; actionId: string; delegationId: string; reason: "EXECUTION_NOT_CONNECTED" }
+ | { callId: string; kind: "playback-reset"; playbackEpoch: number };
+
+export type LiveTranscriptEvent = {
+ callId: string;
+ segment: LiveTranscriptSegment;
+};
diff --git a/packages/shared/src/types/settings.ts b/packages/shared/src/types/settings.ts
index e0fb8754f..4471fd3d2 100644
--- a/packages/shared/src/types/settings.ts
+++ b/packages/shared/src/types/settings.ts
@@ -10,6 +10,7 @@ import type { PluginMarketSource } from "./plugins.js";
import type { SpeechSettings } from "./speech.js";
import type { ThinkingLevel } from "./models.js";
import type { UpdatePreference } from "./platform.js";
+import type { LiveVoiceSettings } from "./live-voice.js";
export type ThemePreference = "system" | "light" | "dark" | `plugin:${string}`;
@@ -35,6 +36,8 @@ export type AppSettings = {
lastNotifiedUpdateVersion?: string;
/** Host speech bindings. Absent means voice actions stay disabled. */
speech?: SpeechSettings;
+ /** App-owned real-time voice bindings; separate from local dictation. */
+ liveVoice?: LiveVoiceSettings;
defaultMode: Mode;
/**
* Keep retryable provider/network failures retrying until the request succeeds.
diff --git a/packages/voice-runtime/package.json b/packages/voice-runtime/package.json
index 6ffdc474a..6252df3ce 100644
--- a/packages/voice-runtime/package.json
+++ b/packages/voice-runtime/package.json
@@ -7,6 +7,10 @@
".": {
"types": "./src/index.ts",
"import": "./dist/index.js"
+ },
+ "./live": {
+ "types": "./src/live/index.ts",
+ "import": "./dist/live/index.js"
}
},
"scripts": {
diff --git a/packages/voice-runtime/src/live/index.ts b/packages/voice-runtime/src/live/index.ts
new file mode 100644
index 000000000..3096d8d06
--- /dev/null
+++ b/packages/voice-runtime/src/live/index.ts
@@ -0,0 +1,3 @@
+export * from "./pcm.js";
+export * from "./protocol.js";
+export * from "./response-tracker.js";
diff --git a/packages/voice-runtime/src/live/pcm.test.ts b/packages/voice-runtime/src/live/pcm.test.ts
new file mode 100644
index 000000000..69f777821
--- /dev/null
+++ b/packages/voice-runtime/src/live/pcm.test.ts
@@ -0,0 +1,60 @@
+import { describe, expect, it } from "vitest";
+import { decodePcm16, encodePcm16, StreamingPcmResampler } from "./pcm.js";
+
+function sine(rate: number, frequency: number, count: number): Float32Array {
+ return Float32Array.from({ length: count }, (_, index) => Math.sin((2 * Math.PI * frequency * index) / rate));
+}
+
+function concat(parts: Float32Array[]): Float32Array {
+ const result = new Float32Array(parts.reduce((sum, item) => sum + item.length, 0));
+ let offset = 0;
+ for (const part of parts) {
+ result.set(part, offset);
+ offset += part.length;
+ }
+ return result;
+}
+
+describe("Live PCM helpers", () => {
+ it("encodes signed PCM16 little-endian with finite clamping", () => {
+ expect([...encodePcm16(Float32Array.of(-2, -0.5, 0, 0.5, 2, Number.NaN))]).toEqual([
+ 0, 128, 0, 192, 0, 0, 0, 64, 255, 127, 0, 0,
+ ]);
+ expect([...decodePcm16(Uint8Array.of(0, 128, 0, 64))]).toEqual([-1, 0.5]);
+ expect(() => decodePcm16(Uint8Array.of(1))).toThrow(RangeError);
+ });
+
+ it("keeps resampling stable across arbitrary input chunk boundaries", () => {
+ const input = sine(44100, 440, 44100);
+ const whole = new StreamingPcmResampler(44100, 16000).push(input);
+ const streaming = new StreamingPcmResampler(44100, 16000);
+ const chunks: Float32Array[] = [];
+ let offset = 0;
+ const sizes = [1, 17, 251, 1024, 93, 311];
+ let sizeIndex = 0;
+ while (offset < input.length) {
+ const end = Math.min(input.length, offset + sizes[sizeIndex++ % sizes.length]);
+ chunks.push(streaming.push(input.subarray(offset, end)));
+ offset = end;
+ }
+ const split = concat(chunks);
+ expect(split.length).toBe(whole.length);
+ let maxDifference = 0;
+ for (let index = 0; index < whole.length; index += 1) {
+ maxDifference = Math.max(maxDifference, Math.abs(whole[index] - split[index]));
+ }
+ expect(maxDifference).toBeLessThan(1e-5);
+ expect(Math.abs(split.length - 16000)).toBeLessThan(16);
+ });
+
+ it("preserves passband tone and suppresses frequencies above the new Nyquist limit", () => {
+ const passband = new StreamingPcmResampler(48000, 16000).push(sine(48000, 1000, 48000));
+ const stopband = new StreamingPcmResampler(48000, 16000).push(sine(48000, 12000, 48000));
+ const rms = (samples: Float32Array) => {
+ const measured = samples.subarray(256, samples.length - 256);
+ return Math.sqrt(measured.reduce((sum, sample) => sum + sample * sample, 0) / measured.length);
+ };
+ expect(rms(passband)).toBeGreaterThan(0.65);
+ expect(rms(stopband)).toBeLessThan(0.03);
+ });
+});
diff --git a/packages/voice-runtime/src/live/pcm.ts b/packages/voice-runtime/src/live/pcm.ts
new file mode 100644
index 000000000..206562ec6
--- /dev/null
+++ b/packages/voice-runtime/src/live/pcm.ts
@@ -0,0 +1,127 @@
+/** Bounded PCM helpers shared by the Live adapters and the renderer worklet. */
+
+const FILTER_TAPS = 49;
+const FILTER_RADIUS = (FILTER_TAPS - 1) / 2;
+const PHASES = 128;
+
+export function encodePcm16(samples: Float32Array): Uint8Array {
+ const output = new Uint8Array(samples.length * 2);
+ const view = new DataView(output.buffer);
+ for (let index = 0; index < samples.length; index += 1) {
+ const value = Number.isFinite(samples[index])
+ ? Math.min(1, Math.max(-1, samples[index]))
+ : 0;
+ view.setInt16(index * 2, value < 0 ? Math.round(value * 32768) : Math.round(value * 32767), true);
+ }
+ return output;
+}
+
+export function decodePcm16(bytes: Uint8Array): Float32Array {
+ if (bytes.byteLength % 2 !== 0) throw new RangeError("PCM16 data must contain whole samples");
+ const output = new Float32Array(bytes.byteLength / 2);
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
+ for (let index = 0; index < output.length; index += 1) {
+ output[index] = view.getInt16(index * 2, true) / 32768;
+ }
+ return output;
+}
+
+function sinc(value: number): number {
+ if (Math.abs(value) < 1e-8) return 1;
+ const angle = Math.PI * value;
+ return Math.sin(angle) / angle;
+}
+
+function coefficients(sourceRate: number, targetRate: number): Float64Array[] {
+ const cutoff = 0.45 * Math.min(1, targetRate / sourceRate);
+ return Array.from({ length: PHASES }, (_, phaseIndex) => {
+ const phase = phaseIndex / PHASES;
+ const taps = new Float64Array(FILTER_TAPS);
+ let total = 0;
+ for (let tap = 0; tap < FILTER_TAPS; tap += 1) {
+ const distance = tap - FILTER_RADIUS - phase;
+ const normalized = distance / (FILTER_RADIUS + 1);
+ const window = 0.42 + 0.5 * Math.cos(Math.PI * normalized) + 0.08 * Math.cos(2 * Math.PI * normalized);
+ const weight = 2 * cutoff * sinc(2 * cutoff * distance) * window;
+ taps[tap] = weight;
+ total += weight;
+ }
+ if (total !== 0) for (let tap = 0; tap < taps.length; tap += 1) taps[tap] /= total;
+ return taps;
+ });
+}
+
+/** Stateful windowed-sinc resampler. Chunk boundaries do not reset its phase. */
+export class StreamingPcmResampler {
+ private input = new Float32Array(0);
+ private inputStart = 0;
+ private totalInput = 0;
+ private nextOutput = 0;
+ private readonly step: number;
+ private readonly phases: Float64Array[];
+
+ constructor(
+ readonly sourceRate: number,
+ readonly targetRate: number,
+ ) {
+ if (!Number.isFinite(sourceRate) || !Number.isFinite(targetRate) || sourceRate < 8000 || targetRate < 8000) {
+ throw new RangeError("Audio sample rates must be finite and at least 8 kHz");
+ }
+ this.step = sourceRate / targetRate;
+ this.phases = coefficients(sourceRate, targetRate);
+ }
+
+ push(chunk: Float32Array): Float32Array {
+ if (this.sourceRate === this.targetRate) {
+ return Float32Array.from(chunk, (sample) => Number.isFinite(sample) ? sample : 0);
+ }
+ this.append(chunk);
+ const output: number[] = [];
+ while (true) {
+ const position = this.nextOutput * this.step;
+ const center = Math.floor(position);
+ if (center + FILTER_RADIUS >= this.totalInput) break;
+ const phaseIndex = Math.min(PHASES - 1, Math.floor((position - center) * PHASES));
+ const taps = this.phases[phaseIndex];
+ let value = 0;
+ for (let tap = 0; tap < FILTER_TAPS; tap += 1) {
+ const sourceIndex = center + tap - FILTER_RADIUS;
+ const localIndex = sourceIndex - this.inputStart;
+ if (sourceIndex >= 0 && localIndex >= 0 && localIndex < this.input.length) {
+ value += this.input[localIndex] * taps[tap];
+ }
+ }
+ output.push(Number.isFinite(value) ? value : 0);
+ this.nextOutput += 1;
+ }
+ this.discardOldSamples();
+ return Float32Array.from(output);
+ }
+
+ reset(): void {
+ this.input = new Float32Array(0);
+ this.inputStart = 0;
+ this.totalInput = 0;
+ this.nextOutput = 0;
+ }
+
+ private append(chunk: Float32Array): void {
+ if (chunk.length === 0) return;
+ const next = new Float32Array(this.input.length + chunk.length);
+ next.set(this.input);
+ for (let index = 0; index < chunk.length; index += 1) {
+ next[this.input.length + index] = Number.isFinite(chunk[index]) ? chunk[index] : 0;
+ }
+ this.input = next;
+ this.totalInput += chunk.length;
+ }
+
+ private discardOldSamples(): void {
+ const nextCenter = Math.floor(this.nextOutput * this.step);
+ const discardThrough = Math.max(0, nextCenter - FILTER_RADIUS);
+ const discardCount = Math.min(this.input.length, discardThrough - this.inputStart);
+ if (discardCount <= 0) return;
+ this.input = this.input.slice(discardCount);
+ this.inputStart += discardCount;
+ }
+}
diff --git a/packages/voice-runtime/src/live/protocol.test.ts b/packages/voice-runtime/src/live/protocol.test.ts
new file mode 100644
index 000000000..d0f1bbdfd
--- /dev/null
+++ b/packages/voice-runtime/src/live/protocol.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from "vitest";
+import {
+ codexDelegationFeedback,
+ geminiSetupMessage,
+ parseCodexMessage,
+ parseGeminiMessage,
+ parseRealtimeMessage,
+ realtimeSessionMatches,
+ realtimeSessionUpdateMessage,
+ realtimeTruncateMessages,
+} from "./protocol.js";
+
+describe("Live wire profiles", () => {
+ it("keeps Codex transcripts visible and answers client delegation without granting execution", () => {
+ expect(parseCodexMessage({ type: "output_transcript.added", text: "Hello there." })).toEqual([
+ { kind: "transcript", role: "assistant", text: "Hello there.", final: true, id: "codex-output" },
+ { kind: "activity", assistantSpeaking: true },
+ ]);
+ expect(parseCodexMessage({
+ type: "delegation.created",
+ item: { type: "delegation", target: "client", id: "delegation-1", content: [{ type: "input_text", text: "Read a local file" }] },
+ })).toEqual([{ kind: "delegation", delegationId: "delegation-1", instruction: "Read a local file" }]);
+ expect(codexDelegationFeedback("delegation-1")).toContain("did not create a new task");
+ });
+
+ it("waits for Gemini setup completion and normalizes every audio part", () => {
+ expect(geminiSetupMessage({ modelId: "gemini-live", voice: "Kore" })).toMatchObject({
+ setup: {
+ model: "models/gemini-live",
+ systemInstruction: { parts: [{ text: expect.stringContaining("no access to files") }] },
+ generationConfig: { responseModalities: ["AUDIO"] },
+ contextWindowCompression: { triggerTokens: "25000", slidingWindow: { targetTokens: "8000" } },
+ },
+ });
+ const bytes = btoa(String.fromCharCode(0, 0, 1, 0));
+ expect(parseGeminiMessage({ setupComplete: {} })).toEqual([{ kind: "ready" }]);
+ const events = parseGeminiMessage({ serverContent: { modelTurn: { parts: [
+ { inlineData: { mimeType: "audio/pcm;rate=24000", data: bytes } },
+ { inlineData: { mimeType: "audio/pcm;rate=24000", data: bytes } },
+ ] }, turnComplete: true } });
+ expect(events.map((event) => event.kind)).toEqual([
+ "audio",
+ "audio",
+ "activity",
+ "turn-complete",
+ "activity",
+ ]);
+ expect(events.slice(0, 2)).toEqual([
+ { kind: "audio", bytes: new Uint8Array([0, 0, 1, 0]) },
+ { kind: "audio", bytes: new Uint8Array([0, 0, 1, 0]) },
+ ]);
+ expect(events.slice(2)).toEqual([
+ { kind: "activity", assistantSpeaking: true },
+ { kind: "turn-complete" },
+ { kind: "activity", assistantSpeaking: false },
+ ]);
+ expect(parseGeminiMessage({ toolCallCancellation: { ids: ["call-1"] } })).toEqual([
+ { kind: "tool-call-cancelled", ids: ["call-1"] },
+ ]);
+ expect(parseGeminiMessage({ serverContent: {
+ interrupted: true,
+ modelTurn: { parts: [{ inlineData: { mimeType: "audio/pcm;rate=24000", data: bytes } }] },
+ } })).toEqual([
+ { kind: "interrupted" },
+ { kind: "activity", assistantSpeaking: false },
+ ]);
+ expect(parseGeminiMessage({ serverContent: { modelTurn: { parts: [{ inlineData: { data: bytes } }] } } })).toEqual([
+ { kind: "error", code: "LIVE_PROTOCOL_ERROR" },
+ ]);
+ });
+
+ it("truncates realtime output at the played cursor after cancelling", () => {
+ expect(realtimeTruncateMessages({ itemId: "item-1", contentIndex: 0, audioEndMs: 825.9 })).toEqual([
+ { type: "response.cancel" },
+ { type: "conversation.item.truncate", item_id: "item-1", content_index: 0, audio_end_ms: 825 },
+ ]);
+ expect(parseRealtimeMessage({ type: "input_audio_buffer.speech_started" })).toEqual([
+ { kind: "activity", userSpeaking: true },
+ { kind: "interrupted" },
+ ]);
+ });
+
+ it("keeps GA and compat-v1 session fields and audio events distinct", () => {
+ const ga = realtimeSessionUpdateMessage({ modelId: "gpt-realtime", voice: "marin", profile: "realtime-ga" }).session as Record<string, unknown>;
+ expect(ga).toMatchObject({ type: "realtime", output_modalities: ["audio"] });
+ expect(ga).toHaveProperty("audio.input.format", { type: "audio/pcm", rate: 24000 });
+ expect(ga).toHaveProperty("audio.output.format", { type: "audio/pcm", rate: 24000 });
+ expect(ga).not.toHaveProperty("input_audio_format");
+ expect(realtimeSessionMatches({ session: ga, modelId: "gpt-realtime", voice: "marin", profile: "realtime-ga" })).toBe(true);
+ expect(realtimeSessionMatches({ session: { ...ga, output_modalities: ["text"] }, modelId: "gpt-realtime", voice: "marin", profile: "realtime-ga" })).toBe(false);
+
+ const compat = realtimeSessionUpdateMessage({ modelId: "gateway-realtime", voice: "cove", profile: "realtime-compat-v1" }).session as Record<string, unknown>;
+ expect(compat).toMatchObject({ modalities: ["text", "audio"], input_audio_format: "pcm16", output_audio_format: "pcm16", voice: "cove" });
+ expect(compat).not.toHaveProperty("type");
+ expect(compat).not.toHaveProperty("audio");
+ expect(compat).not.toHaveProperty("output_modalities");
+ expect(realtimeSessionMatches({ session: compat, modelId: "gateway-realtime", voice: "cove", profile: "realtime-compat-v1" })).toBe(true);
+
+ const audio = btoa(String.fromCharCode(0, 0, 1, 0));
+ expect(parseRealtimeMessage({ type: "response.output_audio.delta", delta: audio, response_id: "ga-response", item_id: "ga-item", content_index: 0 }, "realtime-ga")[0]).toMatchObject({ kind: "audio", responseId: "ga-response", itemId: "ga-item" });
+ expect(parseRealtimeMessage({ type: "response.audio.delta", delta: audio, response_id: "compat-response", item_id: "compat-item", content_index: 0 }, "realtime-compat-v1")[0]).toMatchObject({ kind: "audio", responseId: "compat-response", itemId: "compat-item" });
+ expect(parseRealtimeMessage({ type: "response.audio.delta", delta: audio, response_id: "wrong-profile", item_id: "wrong-profile", content_index: 0 }, "realtime-ga")).toEqual([]);
+ });
+});
diff --git a/packages/voice-runtime/src/live/protocol.ts b/packages/voice-runtime/src/live/protocol.ts
new file mode 100644
index 000000000..72e8e2459
--- /dev/null
+++ b/packages/voice-runtime/src/live/protocol.ts
@@ -0,0 +1,329 @@
+/** Pure wire shaping and bounded event parsing for first-party Live protocols. */
+
+export const MAX_LIVE_JSON_BYTES = 2 * 1024 * 1024;
+export const MAX_LIVE_TEXT_BYTES = 64 * 1024;
+export const MAX_LIVE_AUDIO_BYTES = 512 * 1024;
+
+export type LiveWireEvent =
+ | { kind: "ready" }
+ | { kind: "audio"; bytes: Uint8Array; responseId?: string; itemId?: string; contentIndex?: number }
+ | { kind: "transcript"; role: "user" | "assistant"; text: string; final: boolean; id: string }
+ | { kind: "activity"; userSpeaking?: boolean; assistantSpeaking?: boolean }
+ | { kind: "interrupted" }
+ | { kind: "turn-complete" }
+ | { kind: "delegation"; delegationId: string; instruction: string }
+ | { kind: "tool-call-cancelled"; ids: string[] }
+ | { kind: "closed"; code?: number }
+ | { kind: "error"; code: string };
+
+export function parseCodexMessage(value: unknown): LiveWireEvent[] {
+ const event = record(value);
+ if (!event || typeof event.type !== "string") return [{ kind: "error", code: "LIVE_PROTOCOL_ERROR" }];
+ if (event.type === "delegation.created") {
+ const item = record(event.item);
+ if (!item || item.type !== "delegation" || item.target !== "client") return [];
+ const delegationId = text(item.id, 256);
+ if (!delegationId || !Array.isArray(item.content)) return [{ kind: "error", code: "LIVE_PROTOCOL_ERROR" }];
+ const instruction = item.content.flatMap((part) => {
+ const content = record(part);
+ return content?.type === "input_text" && typeof content.text === "string" ? [content.text] : [];
+ }).join("").trim();
+ if (!instruction || new TextEncoder().encode(instruction).byteLength > 8 * 1024) return [{ kind: "error", code: "LIVE_PROTOCOL_ERROR" }];
+ return [{ kind: "delegation", delegationId, instruction }];
+ }
+ if (event.type === "error") return [{ kind: "error", code: "LIVE_PROTOCOL_ERROR" }];
+ if (event.type === "input_audio_buffer.speech_started") return [{ kind: "activity", userSpeaking: true }];
+ if (event.type === "input_audio_buffer.speech_stopped") return [{ kind: "activity", userSpeaking: false }];
+ if (["output_audio_buffer.started", "response.output_audio.delta", "response.audio.delta"].includes(event.type)) {
+ return [{ kind: "activity", assistantSpeaking: true }];
+ }
+ if (["output_audio_buffer.stopped", "turn.done", "response.done"].includes(event.type)) {
+ return [{ kind: "turn-complete" }, { kind: "activity", assistantSpeaking: false }];
+ }
+ if (event.type === "input_transcript.added" && typeof event.text === "string") {
+ const transcript = text(event.text);
+ return transcript ? [{ kind: "transcript", role: "user", text: transcript, final: true, id: "codex-input" }] : [];
+ }
+ if (event.type === "output_transcript.added" && typeof event.text === "string") {
+ const transcript = text(event.text);
+ return [
+ ...(transcript ? [{ kind: "transcript" as const, role: "assistant" as const, text: transcript, final: true, id: "codex-output" }] : []),
+ { kind: "activity", assistantSpeaking: true },
+ ];
+ }
+ return [];
+}
+
+export function codexDelegationFeedback(delegationId: string): string {
+ return JSON.stringify({
+ type: "delegation.context.append",
+ delegation_item_id: delegationId,
+ channel: "commentary",
+ content: [{
+ type: "input_text",
+ text: "This request did not create a new task. Follow the Host context feedback; do not retry this delegation automatically.",
+ }],
+ });
+}
+
+function record(value: unknown): Record<string, unknown> | null {
+ return value !== null && typeof value === "object" && !Array.isArray(value)
+ ? value as Record<string, unknown>
+ : null;
+}
+
+function text(value: unknown, max = MAX_LIVE_TEXT_BYTES): string | null {
+ if (typeof value !== "string" || value.length === 0 || new TextEncoder().encode(value).byteLength > max) return null;
+ return value;
+}
+
+function decodeBase64(value: unknown): Uint8Array | null {
+ if (typeof value !== "string" || value.length > Math.ceil(MAX_LIVE_AUDIO_BYTES * 4 / 3)) return null;
+ try {
+ const decoded = atob(value);
+ if (decoded.length === 0 || decoded.length > MAX_LIVE_AUDIO_BYTES) return null;
+ const bytes = new Uint8Array(decoded.length);
+ for (let index = 0; index < decoded.length; index += 1) bytes[index] = decoded.charCodeAt(index);
+ return bytes;
+ } catch {
+ return null;
+ }
+}
+
+export function geminiSetupMessage(input: {
+ modelId: string;
+ voice: string;
+}): Record<string, unknown> {
+ return {
+ setup: {
+ model: input.modelId.startsWith("models/") ? input.modelId : `models/${input.modelId}`,
+ systemInstruction: {
+ parts: [{ text: "You are a voice assistant in a conversation. Do not claim to perform actions. You have no access to files, tools, or the coding agent." }],
+ },
+ generationConfig: {
+ responseModalities: ["AUDIO"],
+ speechConfig: { voiceConfig: { prebuiltVoiceConfig: { voiceName: input.voice } } },
+ },
+ realtimeInputConfig: { automaticActivityDetection: { disabled: false } },
+ inputAudioTranscription: {},
+ outputAudioTranscription: {},
+ contextWindowCompression: {
+ triggerTokens: "25000",
+ slidingWindow: { targetTokens: "8000" },
+ },
+ },
+ };
+}
+
+export function geminiAudioMessage(bytes: Uint8Array): Record<string, unknown> {
+ return {
+ realtimeInput: {
+ audio: {
+ mimeType: "audio/pcm;rate=16000",
+ data: bytesToBase64(bytes),
+ },
+ },
+ };
+}
+
+export function geminiAudioEndMessage(): Record<string, unknown> {
+ return { realtimeInput: { audioStreamEnd: true } };
+}
+
+export function parseGeminiMessage(value: unknown): LiveWireEvent[] {
+ const root = record(value);
+ if (!root) return [{ kind: "error", code: "LIVE_PROTOCOL_ERROR" }];
+ if (root.setupComplete !== undefined) return [{ kind: "ready" }];
+ if (root.goAway !== undefined) return [{ kind: "error", code: "LIVE_TIMEOUT" }];
+ const events: LiveWireEvent[] = [];
+ const cancellation = record(root.toolCallCancellation);
+ if (cancellation) {
+ if (!Array.isArray(cancellation.ids) || cancellation.ids.length > 16 || cancellation.ids.some((id) => !text(id, 256))) {
+ return [{ kind: "error", code: "LIVE_PROTOCOL_ERROR" }];
+ }
+ events.push({ kind: "tool-call-cancelled", ids: cancellation.ids as string[] });
+ }
+ const server = record(root.serverContent);
+ if (server) {
+ const interrupted = server.interrupted === true;
+ if (interrupted) events.push({ kind: "interrupted" }, { kind: "activity", assistantSpeaking: false });
+ const inputText = record(server.inputTranscription);
+ const input = text(inputText?.text);
+ if (input) events.push({ kind: "transcript", role: "user", text: input, final: inputText?.finished === true, id: "gemini-input" });
+ const outputText = record(server.outputTranscription);
+ const output = text(outputText?.text);
+ if (output) events.push({ kind: "transcript", role: "assistant", text: output, final: outputText?.finished === true, id: "gemini-output" });
+ const modelTurn = record(server.modelTurn);
+ const parts = Array.isArray(modelTurn?.parts) ? modelTurn.parts : [];
+ for (const part of parts) {
+ const partRecord = record(part);
+ const inline = record(partRecord?.inlineData);
+ if (inline && !interrupted) {
+ if (typeof inline.mimeType !== "string" || !/^audio\/pcm;rate=24000$/i.test(inline.mimeType)) {
+ return [{ kind: "error", code: "LIVE_PROTOCOL_ERROR" }];
+ }
+ const bytes = decodeBase64(inline.data);
+ if (!bytes || bytes.byteLength % 2 !== 0) return [{ kind: "error", code: "LIVE_PROTOCOL_ERROR" }];
+ events.push({ kind: "audio", bytes });
+ }
+ const functionCall = record(partRecord?.functionCall);
+ if (functionCall) {
+ events.push({ kind: "error", code: "LIVE_EXECUTION_NOT_CONNECTED" });
+ }
+ }
+ if (modelTurn && !interrupted) events.push({ kind: "activity", assistantSpeaking: true });
+ if (server.turnComplete === true || server.generationComplete === true) {
+ events.push({ kind: "turn-complete" }, { kind: "activity", assistantSpeaking: false });
+ }
+ }
+ return events;
+}
+
+export function realtimeSessionUpdateMessage(input: {
+ modelId: string;
+ voice: string;
+ profile: "realtime-ga" | "realtime-compat-v1";
+}): Record<string, unknown> {
+ const instructions = "You are a voice assistant. Do not claim to execute actions. There is no access to project files, tools, or the coding agent.";
+ if (input.profile === "realtime-compat-v1") {
+ return {
+ type: "session.update",
+ session: {
+ model: input.modelId,
+ instructions,
+ modalities: ["text", "audio"],
+ voice: input.voice,
+ input_audio_format: "pcm16",
+ output_audio_format: "pcm16",
+ input_audio_transcription: { model: "whisper-1" },
+ turn_detection: { type: "server_vad" },
+ },
+ };
+ }
+ return {
+ type: "session.update",
+ session: {
+ type: "realtime",
+ model: input.modelId,
+ instructions,
+ output_modalities: ["audio"],
+ audio: {
+ input: { format: { type: "audio/pcm", rate: 24000 }, turn_detection: { type: "server_vad" }, transcription: { model: "gpt-4o-mini-transcribe" } },
+ output: { format: { type: "audio/pcm", rate: 24000 }, voice: input.voice },
+ },
+ },
+ };
+}
+
+export function realtimeSessionMatches(input: {
+ session: unknown;
+ modelId: string;
+ voice: string;
+ profile: "realtime-ga" | "realtime-compat-v1";
+}): boolean {
+ const session = record(input.session);
+ if (!session || session.model !== input.modelId) return false;
+ if (input.profile === "realtime-compat-v1") {
+ const detection = record(session.turn_detection);
+ return Array.isArray(session.modalities) && session.modalities.includes("audio") &&
+ session.voice === input.voice && session.input_audio_format === "pcm16" &&
+ session.output_audio_format === "pcm16" && detection?.type === "server_vad";
+ }
+ const audio = record(session.audio);
+ const inputAudio = record(audio?.input);
+ const outputAudio = record(audio?.output);
+ const inputFormat = record(inputAudio?.format);
+ const outputFormat = record(outputAudio?.format);
+ const detection = record(inputAudio?.turn_detection);
+ return session.type === "realtime" && Array.isArray(session.output_modalities) && session.output_modalities.includes("audio") &&
+ inputFormat?.type === "audio/pcm" && inputFormat.rate === 24000 && detection?.type === "server_vad" &&
+ outputFormat?.type === "audio/pcm" && outputFormat.rate === 24000 && outputAudio?.voice === input.voice;
+}
+
+export function realtimeAudioMessage(bytes: Uint8Array): Record<string, unknown> {
+ return { type: "input_audio_buffer.append", audio: bytesToBase64(bytes) };
+}
+
+export function realtimeTruncateMessages(cursor: {
+ itemId: string;
+ contentIndex: number;
+ audioEndMs: number;
+}): Record<string, unknown>[] {
+ return [
+ { type: "response.cancel" },
+ { type: "conversation.item.truncate", item_id: cursor.itemId, content_index: cursor.contentIndex, audio_end_ms: Math.max(0, Math.floor(cursor.audioEndMs)) },
+ ];
+}
+
+export function parseRealtimeMessage(value: unknown, profile: "realtime-ga" | "realtime-compat-v1" = "realtime-ga"): LiveWireEvent[] {
+ const event = record(value);
+ if (!event || typeof event.type !== "string") return [{ kind: "error", code: "LIVE_PROTOCOL_ERROR" }];
+ switch (event.type) {
+ case "session.created":
+ return [];
+ case "session.updated":
+ return [{ kind: "ready" }];
+ case "input_audio_buffer.speech_started":
+ return [{ kind: "activity", userSpeaking: true }, { kind: "interrupted" }];
+ case "input_audio_buffer.speech_stopped":
+ return [{ kind: "activity", userSpeaking: false }];
+ case "response.output_audio.delta":
+ case "response.audio.delta": {
+ if ((event.type === "response.output_audio.delta") !== (profile === "realtime-ga")) return [];
+ const bytes = decodeBase64(event.delta);
+ const itemId = text(event.item_id, 256);
+ const responseId = text(event.response_id, 256);
+ const contentIndex = event.content_index;
+ if (!bytes || !itemId || !responseId || !Number.isSafeInteger(contentIndex) || (contentIndex as number) < 0) return [{ kind: "error", code: "LIVE_PROTOCOL_ERROR" }];
+ return [{ kind: "audio", bytes, responseId, itemId, contentIndex: contentIndex as number }];
+ }
+ case "response.output_audio_transcript.delta":
+ case "response.output_audio_transcript.done":
+ case "response.audio_transcript.delta":
+ case "response.audio_transcript.done":
+ case "response.output_text.delta":
+ case "response.output_text.done": {
+ if (event.type.startsWith("response.audio_transcript.") && profile !== "realtime-compat-v1") return [];
+ if (event.type.startsWith("response.output_audio_transcript.") && profile !== "realtime-ga") return [];
+ if (event.type.startsWith("response.output_text.") && profile !== "realtime-ga") return [];
+ const valueText = text(event.delta) ?? text(event.transcript) ?? text(event.text);
+ if (!valueText) return [];
+ return [{ kind: "transcript", role: "assistant", text: valueText, final: event.type.endsWith(".done"), id: text(event.item_id, 256) ?? "realtime-assistant" }];
+ }
+ case "conversation.item.input_audio_transcription.completed": {
+ const valueText = text(event.transcript);
+ return valueText ? [{ kind: "transcript", role: "user", text: valueText, final: true, id: text(event.item_id, 256) ?? "realtime-user" }] : [];
+ }
+ case "response.created":
+ return [{ kind: "activity", assistantSpeaking: true }];
+ case "response.done":
+ case "response.cancelled":
+ return [{ kind: "turn-complete" }, { kind: "activity", assistantSpeaking: false }];
+ case "error": {
+ const detail = record(event.error);
+ const code = typeof detail?.code === "string" && detail.code.length < 80 ? detail.code : "LIVE_PROTOCOL_ERROR";
+ return [{ kind: "error", code: mapRealtimeError(code) }];
+ }
+ case "response.function_call_arguments.done":
+ case "response.output_item.done":
+ return [];
+ default:
+ return [];
+ }
+}
+
+function mapRealtimeError(code: string): string {
+ if (/rate|quota/i.test(code)) return "LIVE_RATE_LIMITED";
+ if (/unauth|credential|api_key/i.test(code)) return "LIVE_AUTH_REQUIRED";
+ if (/model|unsupported/i.test(code)) return "LIVE_PROTOCOL_UNSUPPORTED";
+ return "LIVE_PROTOCOL_ERROR";
+}
+
+function bytesToBase64(bytes: Uint8Array): string {
+ let binary = "";
+ const chunkSize = 0x8000;
+ for (let offset = 0; offset < bytes.length; offset += chunkSize) {
+ binary += String.fromCharCode(...bytes.subarray(offset, Math.min(bytes.length, offset + chunkSize)));
+ }
+ return btoa(binary);
+}
diff --git a/packages/voice-runtime/src/live/response-tracker.test.ts b/packages/voice-runtime/src/live/response-tracker.test.ts
new file mode 100644
index 000000000..71eae1a37
--- /dev/null
+++ b/packages/voice-runtime/src/live/response-tracker.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from "vitest";
+import { RealtimeResponseTracker } from "./response-tracker.js";
+
+describe("RealtimeResponseTracker", () => {
+ it("cancels active output and drops late audio and completion from an interrupted response", () => {
+ const tracker = new RealtimeResponseTracker();
+ tracker.add("response-old");
+ tracker.interrupt();
+
+ expect(tracker.shouldSendCancel()).toBe(true);
+ expect(tracker.shouldAcceptAudio("response-old")).toBe(false);
+ expect(tracker.finish("response-old")).toBe(true);
+ expect(tracker.shouldSendCancel()).toBe(false);
+ expect(tracker.shouldAcceptAudio("response-old")).toBe(false);
+
+ tracker.add("response-new");
+ expect(tracker.shouldAcceptAudio("response-new")).toBe(true);
+ expect(tracker.finish("response-new")).toBe(false);
+ });
+});
diff --git a/packages/voice-runtime/src/live/response-tracker.ts b/packages/voice-runtime/src/live/response-tracker.ts
new file mode 100644
index 000000000..6d0d7763a
--- /dev/null
+++ b/packages/voice-runtime/src/live/response-tracker.ts
@@ -0,0 +1,36 @@
+const MAX_ACTIVE_RESPONSES = 64;
+const MAX_INTERRUPTED_RESPONSES = 128;
+
+/** Keeps late Realtime audio and completion events from reviving interrupted playback. */
+export class RealtimeResponseTracker {
+ private readonly active = new Set<string>();
+ private readonly interrupted = new Set<string>();
+
+ add(responseId: string): void {
+ this.active.add(responseId);
+ while (this.active.size > MAX_ACTIVE_RESPONSES) this.active.delete(this.active.values().next().value as string);
+ }
+
+ interrupt(): void {
+ for (const responseId of this.active) this.interrupted.add(responseId);
+ while (this.interrupted.size > MAX_INTERRUPTED_RESPONSES) this.interrupted.delete(this.interrupted.values().next().value as string);
+ }
+
+ finish(responseId: string): boolean {
+ this.active.delete(responseId);
+ return this.interrupted.has(responseId);
+ }
+
+ shouldSendCancel(): boolean {
+ return this.active.size > 0;
+ }
+
+ shouldAcceptAudio(responseId: string): boolean {
+ return !this.interrupted.has(responseId);
+ }
+
+ clear(): void {
+ this.active.clear();
+ this.interrupted.clear();
+ }
+}
diff --git a/packages/voice-runtime/vitest.config.ts b/packages/voice-runtime/vitest.config.ts
index 8b5840aca..966f5be0d 100644
--- a/packages/voice-runtime/vitest.config.ts
+++ b/packages/voice-runtime/vitest.config.ts
@@ -2,6 +2,6 @@ import { defineConfig } from "vitest/config";
export default defineConfig({
test: {
- include: ["test/**/*.test.ts"],
+ include: ["test/**/*.test.ts", "src/live/**/*.test.ts"],
},
});