fix: cancel stale voice operations and isolate Android startup

This commit is contained in:
illusia committed 2026-10-01 10:08:18 +08:00
1 parent 8960189bc7
commit e2f0a43762
15 files changed
+913 -174

No files matched your search

+91 -21
View File
@@ -242,6 +242,9 @@ export function useVoiceWebSocket() {
let webrtcPlaybackStream: MediaStream | null = null;
let webrtcPlaybackRetryCleanup: (() => void) | null = null;
let webrtcNegotiationPromise: Promise<void> | null = null;
let webrtcGeneration = 0;
let webrtcAnswerTimer: number | null = null;
let cancelIceGathering: (() => void) | null = null;
let webrtcFallbackStarted = false;
const webrtcActive = ref(false);
const identityMaterial = ref("");
@@ -269,6 +272,8 @@ export function useVoiceWebSocket() {
const accompanimentSupported = ref(typeof navigator !== "undefined" && Boolean(navigator.mediaDevices?.getDisplayMedia));
const accompanimentErrorCode = ref<"" | "unsupported" | "needsWebRtc" | "noAudio" | "permission">("");
let accompanimentStream: MediaStream | null = null;
let accompanimentGeneration = 0;
let accompanimentEndedCleanup: (() => void) | null = null;
const screenShare = createScreenShareController({
isOpen: () => ws.value?.readyState === WebSocket.OPEN,
send: message => ws.value?.send(JSON.stringify(message)),
@@ -513,12 +518,15 @@ export function useVoiceWebSocket() {
if (audioCtx && audioCtx.state === "suspended") {
try { await audioCtx.resume(); } catch { /* a user gesture is still required */ }
}
if (webrtcOutputElement !== output) return;
try {
await output.play();
if (webrtcOutputElement !== output) return;
webrtcPlaybackRetryCleanup?.();
clearAudioNotice("PLAYBACK_BLOCKED");
syncAudioContextNotice();
} catch {
if (webrtcOutputElement !== output) return;
// Mobile and privacy-focused browsers can require a gesture even for a
// MediaStream. Keep retrying after the next real interaction, but tell the
// user why the remote audio is missing instead of staying silent.
@@ -812,6 +820,7 @@ export function useVoiceWebSocket() {
webrtcMixMicSource?.disconnect();
webrtcMixMicGain?.disconnect();
webrtcMixDestination?.disconnect();
webrtcMixDestination?.stream.getTracks().forEach(track => track.stop());
webrtcMixAccompanimentSource = null;
webrtcMixMicSource = null;
webrtcMixMicGain = null;
@@ -819,6 +828,9 @@ export function useVoiceWebSocket() {
}
function releaseAccompanimentStream(): void {
accompanimentGeneration++;
accompanimentEndedCleanup?.();
accompanimentEndedCleanup = null;
accompanimentStream?.getTracks().forEach((track) => track.stop());
accompanimentStream = null;
accompanimentActive.value = false;
@@ -877,6 +889,11 @@ export function useVoiceWebSocket() {
accompanimentErrorCode.value = "needsWebRtc";
throw new Error("伴奏功能需要启用 WebRTC");
}
const generation = ++accompanimentGeneration;
const peer = webrtcPeer;
const sequence = connectionSequence;
const isCurrent = (): boolean => generation === accompanimentGeneration
&& sequence === connectionSequence && webrtcPeer === peer && webrtcActive.value;
const captureProcessingConstraints: MediaTrackConstraints = {
// Display/application audio must not pass through browser voice
@@ -902,10 +919,15 @@ export function useVoiceWebSocket() {
try {
nextStream = await navigator.mediaDevices.getDisplayMedia(options);
} catch (error) {
if (!isCurrent()) return;
if (error instanceof DOMException && error.name === "AbortError") return;
accompanimentErrorCode.value = "permission";
throw error;
}
if (!isCurrent()) {
nextStream.getTracks().forEach(track => track.stop());
return;
}
const audioTrack = nextStream.getAudioTracks()[0];
nextStream.getVideoTracks().forEach((track) => track.stop());
if (!audioTrack) {
@@ -924,16 +946,26 @@ export function useVoiceWebSocket() {
// processing constraints. The capture can still proceed without
// introducing a WebSpeak-side gain stage.
}
if (!isCurrent()) {
nextStream.getTracks().forEach(track => track.stop());
return;
}
if ("contentHint" in audioTrack) audioTrack.contentHint = "music";
accompanimentEndedCleanup?.();
accompanimentStream?.getTracks().forEach((track) => track.stop());
accompanimentStream = nextStream;
accompanimentActive.value = true;
sendCmd("setAccompanimentActive", { active: true });
audioTrack.addEventListener("ended", () => { void stopAccompaniment(); }, { once: true });
const onEnded = (): void => {
if (accompanimentStream === nextStream) void stopAccompaniment().catch(() => undefined);
};
audioTrack.addEventListener("ended", onEnded, { once: true });
accompanimentEndedCleanup = () => audioTrack.removeEventListener("ended", onEnded);
try {
await replaceWebRtcAudioTrack();
} catch (error) {
if (!isCurrent() || accompanimentStream !== nextStream) return;
releaseAccompanimentStream();
sendCmd("setAccompanimentActive", { active: false });
stopWebRtcMix();
@@ -952,21 +984,39 @@ export function useVoiceWebSocket() {
async function startWebRtcTransport(sequence: number, socket: WebSocket): Promise<void> {
if (typeof RTCPeerConnection === "undefined") throw new Error("当前浏览器不支持 WebRTC");
await ensureMicrophone();
if (sequence !== connectionSequence || socket.readyState !== WebSocket.OPEN || !micStream) return;
stopWebRtcTransport();
const generation = webrtcGeneration;
const isCurrent = (): boolean => generation === webrtcGeneration && sequence === connectionSequence
&& ws.value === socket && socket.readyState === WebSocket.OPEN && state.connected;
try { await ensureMicrophone(); } catch (error) {
if (isCurrent()) throw error;
return;
}
if (!isCurrent() || !micStream) return;
const microphoneTrack = micStream.getAudioTracks()[0];
if (!microphoneTrack) throw new Error("没有可用的麦克风音轨");
stopCaptureGraph();
const peer = new RTCPeerConnection({ iceServers: [] });
webrtcPeer = peer;
webrtcFallbackStarted = false;
microphoneTrack.enabled = !microphoneMuted.value;
const mixedStream = createWebRtcMixStream();
const mixedTrack = mixedStream.getAudioTracks()[0];
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
peer.addTrack(mixedTrack, mixedStream);
let peer: RTCPeerConnection;
try { peer = new RTCPeerConnection({ iceServers: [] }); } catch {
await fallbackFromWebRtc(sequence, socket, "WEBRTC_NEGOTIATION_FAILED");
return;
}
webrtcPeer = peer;
const isCurrentPeer = (): boolean => isCurrent() && webrtcPeer === peer;
try {
microphoneTrack.enabled = !microphoneMuted.value;
const mixedStream = createWebRtcMixStream();
const mixedTrack = mixedStream.getAudioTracks()[0];
if (!mixedTrack) throw new Error("混合音频轨道创建失败");
peer.addTrack(mixedTrack, mixedStream);
} catch {
await fallbackFromWebRtc(sequence, socket, "WEBRTC_NEGOTIATION_FAILED");
return;
}
peer.ontrack = (event) => {
if (!isCurrentPeer()) return;
const stream = event.streams[0] ?? new MediaStream([event.track]);
// Use the browser's native WebRTC media output. Routing the remote
// track through AudioContext made playback depend on autoplay policy:
@@ -997,15 +1047,17 @@ export function useVoiceWebSocket() {
};
startWebRtcMicMonitor(getAudioCtx(), micStream, microphoneTrack);
peer.onconnectionstatechange = () => {
if (peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket, "WEBRTC_CONNECTION_FAILED");
if (isCurrentPeer() && peer.connectionState === "failed") void fallbackFromWebRtc(sequence, socket, "WEBRTC_CONNECTION_FAILED");
};
const negotiation = (async () => {
webrtcActive.value = true;
const offer = await peer.createOffer();
if (!isCurrentPeer()) return;
await peer.setLocalDescription(offer);
if (!isCurrentPeer()) return;
await waitForIceGathering(peer);
if (sequence !== connectionSequence || webrtcPeer !== peer || socket.readyState !== WebSocket.OPEN) return;
if (!isCurrentPeer()) return;
const description = peer.localDescription;
if (!description) throw new Error("WebRTC offer was not created");
socket.send(JSON.stringify({ type: "webrtcOffer", payload: {
@@ -1013,16 +1065,16 @@ export function useVoiceWebSocket() {
muted: microphoneMuted.value,
accompanimentActive: accompanimentActive.value,
} }));
window.setTimeout(() => {
if (webrtcPeer === peer && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket, "WEBRTC_ANSWER_TIMEOUT");
webrtcAnswerTimer = window.setTimeout(() => {
webrtcAnswerTimer = null;
if (isCurrentPeer() && !peer.remoteDescription) void fallbackFromWebRtc(sequence, socket, "WEBRTC_ANSWER_TIMEOUT");
}, 8_000);
})();
webrtcNegotiationPromise = negotiation;
try {
await negotiation;
} catch (error) {
if (webrtcPeer === peer) await fallbackFromWebRtc(sequence, socket, "WEBRTC_NEGOTIATION_FAILED");
throw error;
if (isCurrentPeer()) await fallbackFromWebRtc(sequence, socket, "WEBRTC_NEGOTIATION_FAILED");
} finally {
if (webrtcNegotiationPromise === negotiation) webrtcNegotiationPromise = null;
}
@@ -1037,29 +1089,39 @@ export function useVoiceWebSocket() {
settled = true;
window.clearTimeout(timer);
peer.removeEventListener("icegatheringstatechange", onStateChange);
if (cancelIceGathering === finish) cancelIceGathering = null;
resolve();
};
const onStateChange = () => {
if (peer.iceGatheringState === "complete") finish();
};
const timer = window.setTimeout(finish, 5_000);
cancelIceGathering = finish;
peer.addEventListener("icegatheringstatechange", onStateChange);
});
}
async function applyWebRtcAnswer(description: unknown): Promise<void> {
if (!webrtcPeer || !isSessionDescription(description, "answer")) return;
const peer = webrtcPeer;
const socket = ws.value;
const sequence = connectionSequence;
if (!peer || !socket || !isSessionDescription(description, "answer")) return;
const isCurrent = (): boolean => webrtcPeer === peer && ws.value === socket
&& sequence === connectionSequence && socket.readyState === WebSocket.OPEN && state.connected;
try {
await webrtcPeer.setRemoteDescription(description);
await peer.setRemoteDescription(description);
if (!isCurrent()) return;
if (webrtcAnswerTimer !== null) window.clearTimeout(webrtcAnswerTimer);
webrtcAnswerTimer = null;
webrtcActive.value = true;
syncWebRtcMemberVolumes();
} catch {
if (lastConnection && ws.value) await fallbackFromWebRtc(connectionSequence, ws.value, "WEBRTC_ANSWER_REJECTED");
if (isCurrent()) await fallbackFromWebRtc(sequence, socket, "WEBRTC_ANSWER_REJECTED");
}
}
async function fallbackFromWebRtc(sequence: number, socket: WebSocket, reasonCode = "WEBRTC_UNAVAILABLE"): Promise<void> {
if (sequence !== connectionSequence || webrtcFallbackStarted) return;
if (sequence !== connectionSequence || ws.value !== socket || !state.connected || webrtcFallbackStarted) return;
webrtcFallbackStarted = true;
webrtcActive.value = false;
if (socket.readyState === WebSocket.OPEN) socket.send(JSON.stringify({ type: "webrtcStop" }));
@@ -1075,15 +1137,23 @@ export function useVoiceWebSocket() {
}
function stopWebRtcTransport(): void {
webrtcGeneration++;
const peer = webrtcPeer;
webrtcPeer = null;
if (webrtcAnswerTimer !== null) window.clearTimeout(webrtcAnswerTimer);
webrtcAnswerTimer = null;
cancelIceGathering?.();
webrtcActive.value = false;
webrtcNegotiationPromise = null;
releaseAccompanimentStream();
stopWebRtcMix();
stopWebRtcMicMonitor();
stopWebRtcPlayback();
if (peer) void peer.close();
if (peer) {
peer.ontrack = null;
peer.onconnectionstatechange = null;
peer.close();
}
}
function stopWebRtcPlayback(): void {
+2 -56
View File
@@ -1,8 +1,7 @@
import { createApp } from "vue";
import { createPinia } from "pinia";
import { createRouter, createWebHistory } from "vue-router";
import { Capacitor } from "@capacitor/core";
import { Nodejs } from "@capawesome/capacitor-nodejs";
import { bootstrapPlatform } from "./platform/bootstrap.js";
import App from "./App.vue";
import WebClient from "./views/WebClient.vue";
import AdminView from "./views/AdminView.vue";
@@ -40,11 +39,7 @@ const router = createRouter({
routes,
});
if (Capacitor.isNativePlatform() && !(location.hostname === "127.0.0.1" && location.port === "3040")) {
void startAndroidGateway();
} else {
mountApp();
}
void bootstrapPlatform(mountApp);
function mountApp(): void {
const app = createApp(App);
@@ -52,52 +47,3 @@ function mountApp(): void {
app.use(router);
app.mount("#app");
}
async function startAndroidGateway(): Promise<void> {
const root = document.getElementById("app");
if (!root) return;
root.innerHTML = '<main style="min-height:100dvh;display:grid;place-items:center;background:#e9fbfb;color:#0b5960;font:16px system-ui;text-align:center;padding:24px"><div><h1 style="font-size:26px">WebSpeak</h1><p id="mobile-gateway-status">正在启动本地语音服务…</p></div></main>';
const status = document.getElementById("mobile-gateway-status");
let complete = false;
let pollTimer = 0;
let timeoutTimer = 0;
try {
const listener = await Nodejs.addListener("message", (event) => {
if (complete) return;
if (event.eventName === "webspeak-error") {
complete = true;
window.clearInterval(pollTimer);
window.clearTimeout(timeoutTimer);
if (status) status.textContent = "本地语音服务启动失败,请重新打开应用。";
return;
}
if (event.eventName !== "webspeak-health") return;
const health = event.args[0];
if (!health || typeof health !== "object" || Array.isArray(health) || health.ready !== true) return;
complete = true;
window.clearInterval(pollTimer);
window.clearTimeout(timeoutTimer);
void listener.remove();
window.location.replace("http://127.0.0.1:3040/");
});
const poll = async () => {
if (complete) return;
const { ready } = await Nodejs.isReady();
if (ready) await Nodejs.send({ eventName: "webspeak-health", args: [] });
};
pollTimer = window.setInterval(() => { void poll().catch(() => {}); }, 500);
timeoutTimer = window.setTimeout(() => {
if (complete) return;
complete = true;
window.clearInterval(pollTimer);
if (status) status.textContent = "本地语音服务启动超时,请重新打开应用。";
}, 45_000);
await poll();
} catch {
complete = true;
window.clearInterval(pollTimer);
window.clearTimeout(timeoutTimer);
if (status) status.textContent = "本地语音服务启动失败,请重新打开应用。";
}
}
+101
View File
@@ -0,0 +1,101 @@
import type { MessageEvent as NodeMessage, SendOptions } from "@capawesome/capacitor-nodejs";
export interface AndroidGatewayBridge {
addListener(name: "message", callback: (message: NodeMessage) => void): Promise<{ remove(): Promise<void> }>;
isReady(): Promise<{ ready: boolean }>;
send(options: SendOptions): Promise<void>;
}
export class GatewayStartupError extends Error {
constructor(public readonly code: "failed" | "timeout" | "cancelled") {
super(`Android gateway startup ${code}`);
}
}
/** One startup attempt owns its listener, polling timer and deadline. */
export function waitForAndroidGateway(
bridge: AndroidGatewayBridge,
options: { signal?: AbortSignal; timeoutMs?: number; pollIntervalMs?: number } = {},
): Promise<void> {
return new Promise((resolve, reject) => {
let complete = false;
let polling = false;
let listener: { remove(): Promise<void> } | null = null;
let pollTimer: ReturnType<typeof setInterval> | null = null;
let deadline: ReturnType<typeof setTimeout> | null = null;
const remove = (handle: { remove(): Promise<void> }): void => {
try { void handle.remove().catch(() => undefined); } catch { /* plugin may already be disposed */ }
};
const finish = (error?: GatewayStartupError): void => {
if (complete) return;
complete = true;
if (pollTimer !== null) clearInterval(pollTimer);
if (deadline !== null) clearTimeout(deadline);
options.signal?.removeEventListener("abort", cancel);
if (listener) { remove(listener); listener = null; }
if (error) reject(error);
else resolve();
};
const cancel = (): void => finish(new GatewayStartupError("cancelled"));
if (options.signal?.aborted) { cancel(); return; }
options.signal?.addEventListener("abort", cancel, { once: true });
// Include listener registration in the deadline: a missing plugin must not
// leave the initial app screen waiting indefinitely.
deadline = setTimeout(() => finish(new GatewayStartupError("timeout")), options.timeoutMs ?? 45_000);
const poll = async (): Promise<void> => {
if (complete || polling) return;
polling = true;
try {
const { ready } = await bridge.isReady();
if (!complete && ready) await bridge.send({ eventName: "webspeak-health", args: [] });
} catch {
finish(new GatewayStartupError("failed"));
} finally { polling = false; }
};
void Promise.resolve().then(() => bridge.addListener("message", event => {
if (complete) return;
if (event.eventName === "webspeak-error") { finish(new GatewayStartupError("failed")); return; }
if (event.eventName !== "webspeak-health") return;
const health = event.args[0];
if (health && typeof health === "object" && !Array.isArray(health) && health.ready === true) finish();
})).then(handle => {
// Some plugins deliver the first message before addListener resolves.
// A timeout/cancellation can also win this race; release the late handle.
if (complete) { remove(handle); return; }
listener = handle;
pollTimer = setInterval(() => { void poll(); }, options.pollIntervalMs ?? 500);
void poll();
}, () => finish(new GatewayStartupError("failed")));
});
}
export async function startAndroidGateway(): Promise<void> {
const root = document.getElementById("app");
if (!root) return;
root.innerHTML = '<main style="min-height:100dvh;display:grid;place-items:center;background:#e9fbfb;color:#0b5960;font:16px system-ui;text-align:center;padding:24px"><div><h1 style="font-size:26px">WebSpeak</h1><p id="mobile-gateway-status">正在启动本地语音服务…</p><button id="mobile-gateway-retry" type="button" hidden>重试</button></div></main>';
const status = root.querySelector("#mobile-gateway-status");
const retry = root.querySelector<HTMLButtonElement>("#mobile-gateway-retry");
const controller = new AbortController();
const cancel = (): void => controller.abort();
window.addEventListener("pagehide", cancel, { once: true });
try {
const { Nodejs } = await import("@capawesome/capacitor-nodejs");
await waitForAndroidGateway(Nodejs, { signal: controller.signal });
if (!controller.signal.aborted) window.location.replace("http://127.0.0.1:3040/");
} catch (error) {
if (controller.signal.aborted) return;
if (status) status.textContent = error instanceof GatewayStartupError && error.code === "timeout"
? "本地语音服务启动超时,请重试或重新打开应用。"
: "本地语音服务启动失败,请重试或重新打开应用。";
if (retry) {
retry.hidden = false;
// This retries the readiness handshake; the embedded runtime itself can
// only be started once per app launch.
retry.addEventListener("click", () => { void startAndroidGateway(); }, { once: true });
}
} finally {
window.removeEventListener("pagehide", cancel);
}
}
+14
View File
@@ -0,0 +1,14 @@
import { Capacitor } from "@capacitor/core";
export function needsEmbeddedGateway(native: boolean, address: Pick<Location, "hostname" | "port">): boolean {
return native && !(address.hostname === "127.0.0.1" && address.port === "3040");
}
export async function bootstrapPlatform(mount: () => void): Promise<void> {
if (needsEmbeddedGateway(Capacitor.isNativePlatform(), location)) {
const { startAndroidGateway } = await import("./android-gateway.js");
await startAndroidGateway();
} else {
mount();
}
}