Skip to content

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

fix(live-voice): confirm capture release before teardown

vastsac570800e8517
diff --git a/apps/desktop/src/features/voice/live/live-call-controller.ts b/apps/desktop/src/features/voice/live/live-call-controller.ts
index 5b9f47541..d032ba52f 100644
--- a/apps/desktop/src/features/voice/live/live-call-controller.ts
+++ b/apps/desktop/src/features/voice/live/live-call-controller.ts
@@ -38,7 +38,10 @@ const ICE_GATHER_TIMEOUT_MS = 10_000;
type StartResources = {
requestId: string;
callId?: string;
+ microphoneRequest?: Promise<MediaStream>;
+ microphoneRequestSettled?: boolean;
stream?: MediaStream;
+ streamStopped?: boolean;
context?: AudioContext;
port?: MessagePort;
pcm?: LivePcmSession;
@@ -149,9 +152,14 @@ export class LiveCallController {
}
}).catch(() => undefined);
micRequest = requestMicrophone(this.microphoneDeviceId);
+ resources.microphoneRequest = micRequest;
void micRequest.then((stream) => {
- if (resources.abort.signal.aborted || generation !== this.generation) stopStream(stream);
- }).catch(() => undefined);
+ resources.microphoneRequestSettled = true;
+ resources.stream = stream;
+ if (resources.abort.signal.aborted || generation !== this.generation) this.stopCapture(resources);
+ }, () => {
+ resources.microphoneRequestSettled = true;
+ });
if (selected.adapterId !== "codex-live" || options.workTarget) {
resources.context = new AudioContext({ sampleRate: 48_000 });
void resources.context.resume().catch(() => undefined);
@@ -683,26 +691,44 @@ export class LiveCallController {
});
}
if (notifyMain && resources.callId && !resources.releaseReportPromise) {
- resources.releaseReportPromise = resources.releasePromise.then(async (released) => {
- if (!released) {
- resources.releaseAckSettled = true;
- this.completeResourceLifecycle(resources);
- return;
- }
- try {
+ const released = resources.pcm
+ ? resources.releasePromise.then((ok) => {
+ if (!ok) throw liveError("LIVE_MEDIA_RELEASE_UNCONFIRMED");
+ })
+ : this.reportMicrophoneReleased(resources).then(async () => {
await liveVoiceApi.reportMedia({ callId: resources.callId!, kind: "released" });
- } catch {
- resources.releaseFailed = true;
- this.patch({ errorCode: "LIVE_MEDIA_RELEASE_UNCONFIRMED" });
- } finally {
- resources.releaseAckSettled = true;
- this.completeResourceLifecycle(resources);
- }
+ });
+ resources.releaseReportPromise = released.catch(() => {
+ resources.releaseFailed = true;
+ this.patch({ errorCode: "LIVE_MEDIA_RELEASE_UNCONFIRMED" });
+ }).finally(() => {
+ resources.releaseAckSettled = true;
+ this.completeResourceLifecycle(resources);
});
}
return resources.releaseReportPromise ?? resources.releasePromise.then(() => undefined);
}
+ private async reportMicrophoneReleased(resources: StartResources): Promise<void> {
+ if (resources.microphoneRequest && !resources.microphoneRequestSettled) {
+ await resources.microphoneRequest.then(() => undefined, () => undefined);
+ }
+ if (!this.stopCapture(resources)) {
+ throw liveError("LIVE_MEDIA_RELEASE_UNCONFIRMED");
+ }
+ }
+
+ private stopCapture(resources: StartResources): boolean {
+ if (resources.streamStopped || !resources.stream) return true;
+ try {
+ stopStream(resources.stream);
+ resources.streamStopped = true;
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
private async releaseResourcesOnce(resources: StartResources): Promise<boolean> {
let released = true;
const cleanup = (action: () => void) => {
@@ -714,13 +740,13 @@ export class LiveCallController {
if (resources.heartbeat) clearInterval(resources.heartbeat);
resources.abort.abort();
cleanup(() => this.stopPlaybackMonitor(resources));
- if (resources.stream) cleanup(() => stopStream(resources.stream!));
- if (resources.channel) cleanup(() => resources.channel!.close());
- if (resources.peer) cleanup(() => resources.peer!.close());
- if (resources.audio) cleanup(() => {
- resources.audio!.pause();
- resources.audio!.srcObject = null;
- resources.audio!.remove();
+ if (!this.stopCapture(resources)) released = false;
+ cleanup(() => resources.channel?.close());
+ cleanup(() => resources.peer?.close());
+ cleanup(() => {
+ resources.audio?.pause();
+ if (resources.audio) resources.audio.srcObject = null;
+ resources.audio?.remove();
});
if (resources.pcm) await cleanupAsync(() => resources.pcm?.release());
if (!resources.pcm && resources.context && resources.context.state !== "closed") {
diff --git a/apps/desktop/src/features/voice/live/live-pcm-session.ts b/apps/desktop/src/features/voice/live/live-pcm-session.ts
index 2a63e5ed9..4c06d51b6 100644
--- a/apps/desktop/src/features/voice/live/live-pcm-session.ts
+++ b/apps/desktop/src/features/voice/live/live-pcm-session.ts
@@ -130,20 +130,26 @@ export class LivePcmSession {
this.source.disconnect();
this.node.port.postMessage({ kind: "release" });
this.node.disconnect();
+ this.acknowledgeRelease();
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 acknowledgeRelease(): void {
+ if (this.releaseSent) return;
+ this.releaseSent = true;
+ try {
+ this.port.postMessage({ kind: "released", callId: this.callId });
+ } catch {
+ // The main side may have closed the port after confirming capture stopped.
+ }
+ }
+
private waitForReady(signal: AbortSignal): Promise<void> {
if (this.portReady) return Promise.resolve();
return new Promise<void>((resolve, reject) => {
diff --git a/scripts/e2e-live-voice.mjs b/scripts/e2e-live-voice.mjs
index 492b41d92..b6fb5cf78 100644
--- a/scripts/e2e-live-voice.mjs
+++ b/scripts/e2e-live-voice.mjs
@@ -34,8 +34,10 @@ const settings = () => desktop.invoke("settingsGet");
const status = () => desktop.invoke("liveVoiceStatus");
const waitIdle = () => waitFor(async () => {
const call = (await status()).call;
- return !call || (["ended", "failed"].includes(call.phase) && !call.microphoneActive);
-}, 12_000, "Live call media released");
+ const mediaReleased = !call || (["ended", "failed"].includes(call.phase) && !call.microphoneActive);
+ if (!mediaReleased) return false;
+ return desktop.evaluate("!document.querySelector('.live-voice-call-bar[data-state=\"connecting\"], .live-voice-call-bar[data-state=\"connected\"], .live-voice-call-bar[data-state=\"reconnecting\"], .live-voice-call-bar[data-state=\"stopping\"]') && !!document.querySelector('.live-voice-control button')");
+}, 12_000, "Live call media and Composer controls released");
const navVoice = () => desktop.clickText("Live voice", ".settings-nav-label");
const openSettings = async () => {
await desktop.clickSelector('[data-nav="settings"]');
@@ -45,12 +47,17 @@ const openSettings = async () => {
};
const backToChat = () => desktop.clickSelector('[data-nav="back-to-app"]');
const startCall = async () => {
- await desktop.clickSelector('.live-voice-control button[aria-label="Start Live voice"]');
+ const previousCallId = (await status()).call?.callId;
+ await desktop.clickSelector(".live-voice-control button");
+ await waitFor(() => desktop.evaluate("!!document.querySelector('.live-voice-preparation .live-voice-start')"),
+ 5_000, "Live Voice preparation menu");
+ await desktop.clickSelector(".live-voice-preparation .live-voice-start");
await waitFor(async () => {
const [live, error] = await Promise.all([
- status(), desktop.evaluate("!!document.querySelector('.live-voice-error[role=\"alert\"]')"),
+ status(), desktop.evaluate("!!document.querySelector('.live-voice-feedback[role=\"alert\"]')"),
]);
- return live.call?.phase === "connected" || (error && ["ended", "failed"].includes(live.call?.phase));
+ const newCall = Boolean(live.call && live.call.callId !== previousCallId);
+ return newCall && (live.call?.phase === "connected" || (error && ["ended", "failed"].includes(live.call?.phase)));
}, 30_000, "local Realtime connected or startup failed");
assert.equal((await status()).call?.phase, "connected", "local Realtime call connected");
};
@@ -84,12 +91,10 @@ try {
assert.equal(initial.liveVoice?.enabled ?? false, false);
assert.equal((await status()).enabled, false);
assert.equal(fixture.stats.connections, 0);
- await desktop.clickSelector('.live-voice-control button[aria-label="Start Live voice"]');
- await desktop.clickText("Open settings", ".live-voice-panel button");
- await waitFor(() => desktop.evaluate("!!document.querySelector('.live-voice-settings')"), 10_000, "Composer setup navigation");
+ await openSettings();
assert.equal(fixture.stats.connections, 0);
await desktop.screenshot("live-voice-disabled.png");
- pass("ordinary-user Composer setup opens Voice without starting capture");
+ pass("ordinary users can reach Voice settings without starting capture");
await desktop.input(".settings-search", "Live voice");
await waitFor(() => desktop.evaluate("[...document.querySelectorAll('.settings-nav-label')].some(el => el.textContent.trim() === 'Live voice')"), 5_000, "Voice search match");
@@ -124,29 +129,32 @@ try {
await startCall();
assert.equal((await status()).call.muted, true);
assert.equal((await status()).call.workBinding, undefined);
- await desktop.clickText("Unmute microphone", ".live-voice-panel button");
+ await desktop.clickSelector('.live-voice-call-bar button[aria-label="Unmute microphone"]');
await waitFor(() => fixture.stats.inputFrames > 0, 10_000, "synthetic microphone reaches the real WSS transport");
await waitFor(async () => (await status()).call?.phase === "connected" && fixture.active() === 1,
2_000, "uplink credit keeps the call and provider socket connected");
fixture.reply();
+ await desktop.clickSelector('.live-voice-call-bar button[aria-label="Call details"]');
await waitFor(() => desktop.evaluate("document.querySelector('.live-voice-transcripts')?.textContent.includes('Local voice fixture reply.')"), 8_000, "provider transcript reaches Renderer");
await desktop.screenshot("live-voice-connected.png");
- await desktop.clickText("Mute microphone", ".live-voice-panel button");
+ await desktop.clickSelector('.live-voice-details-popup button[aria-label="Close"]');
+ await desktop.clickSelector('.live-voice-call-bar button[aria-label="Mute microphone"]');
await waitFor(async () => (await status()).call?.muted === true, 5_000, "microphone muted");
await delay(200);
const mutedFrames = fixture.stats.inputFrames;
await delay(300);
assert.equal(fixture.stats.inputFrames, mutedFrames, "muting stops new provider audio frames");
- await desktop.clickText("End call", ".live-voice-panel button");
+ await desktop.clickSelector('.live-voice-call-bar button[aria-label="End call"]');
await waitIdle();
await waitFor(() => fixture.active() === 0, 5_000, "provider socket closes after hangup");
assert.deepEqual((await desktop.invoke("sessionList")).sessions, [], "voice-only call creates no Agent session");
pass("real Realtime socket, synthetic capture, playback/transcript, mute and hangup");
fixture.holdNextSession();
- await desktop.clickSelector('.live-voice-control button[aria-label="Start Live voice"]');
+ await desktop.clickSelector(".live-voice-control button");
+ await desktop.clickSelector(".live-voice-preparation .live-voice-start");
await waitFor(async () => (await status()).call?.phase === "connecting", 15_000, "delayed provider startup");
- await desktop.clickText("Cancel", ".live-voice-panel button");
+ await desktop.clickSelector('.live-voice-call-bar button[aria-label="Cancel"]');
await waitIdle();
await waitFor(() => fixture.active() === 0, 5_000, "cancelled provider socket closes");
await startCall();
@@ -156,7 +164,7 @@ try {
await delay(500);
assert.equal(fixture.stats.connections, disconnectedConnections, "provider failure never auto-reconnects");
await startCall();
- await desktop.clickText("End call", ".live-voice-panel button");
+ await desktop.clickSelector('.live-voice-call-bar button[aria-label="End call"]');
await waitIdle();
pass("cancelled startup and provider failure release resources for explicit reconnect");
@@ -187,8 +195,12 @@ try {
} catch (error) {
await desktop?.screenshot("live-voice-failure.png").catch(() => undefined);
const current = await desktop?.invoke("liveVoiceStatus").catch(() => null);
- const callFailure = current?.call?.error
- ? { code: current.call.error.code, stage: current.call.error.stage }
+ const callFailure = current?.call
+ ? {
+ code: current.call.error?.code,
+ stage: current.call.error?.stage,
+ mediaRelease: current.call.mediaRelease,
+ }
: null;
console.error(`Live Voice E2E failed: ${error.message}; phase=${current?.call?.phase ?? "none"}; callFailure=${JSON.stringify(callFailure)}; fixture=${JSON.stringify({ ...fixture.stats, active: fixture.active(), errors: fixture.errors })}`);
throw error;