Skip to content

Commit ba4cd90

Browse files
committed
fix(voice-call): share webhook runtime across contexts
1 parent 250d13d commit ba4cd90

3 files changed

Lines changed: 175 additions & 63 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@ Docs: https://docs.openclaw.ai
6868
- Discord/subagents: preserve thread-bound completion delivery by keeping the requester-agent announce path primary and falling back to direct thread sends only when the announce produces no visible output. (#71064) Thanks @DolencLuka.
6969
- Browser/tool: give Chrome MCP existing-session manage calls a longer default timeout, pass explicit tool timeouts through tab management, and recover stale selected-page MCP sessions instead of forcing a manual reset. Thanks @steipete.
7070
- Browser/sandbox: clean up idle tracked tabs opened by primary-agent browser sessions, while preserving active tab reuse and lifecycle cleanup for subagents, cron, and ACP sessions. Fixes #71165. Thanks @dwbutler.
71+
- Plugins/Voice Call: reuse the webhook runtime across in-process plugin contexts, avoiding `EADDRINUSE` when agent tools or CLI commands run while the Gateway already owns the voice webhook port. Fixes #58115. Thanks @sfbrian.
7172
- Plugins/Voice Call: pin voice response sessions to `responseModel` before embedded agent runs, avoiding live-session model switch failures when the global default model differs. Fixes #60118. Thanks @xinbenlv.
7273
- Media tools: honor the configured web-fetch SSRF policy for media understanding, image/music/video generation references, and PDF inputs, so explicit RFC2544 opt-ins cover WebChat OSS uploads without weakening defaults. Fixes #71300. (#71321) Thanks @neeravmakwana.
7374
- Agents/TTS: suppress successful spoken transcripts from verbose chat tool output when structured voice media is already queued, while preserving text output for non-builtin tool-name collisions. Fixes #71282. Thanks @neeravmakwana.

‎extensions/voice-call/index.test.ts‎

Lines changed: 92 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -5,20 +5,9 @@ import { Command } from "commander";
55
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
66
import { createTestPluginApi } from "../../test/helpers/plugins/plugin-api.ts";
77
import type { OpenClawPluginApi } from "./api.js";
8+
import type { VoiceCallRuntime } from "./runtime-entry.js";
89

9-
let runtimeStub: {
10-
config: { toNumber?: string };
11-
manager: {
12-
initiateCall: ReturnType<typeof vi.fn>;
13-
continueCall: ReturnType<typeof vi.fn>;
14-
speak: ReturnType<typeof vi.fn>;
15-
sendDtmf: ReturnType<typeof vi.fn>;
16-
endCall: ReturnType<typeof vi.fn>;
17-
getCall: ReturnType<typeof vi.fn>;
18-
getCallByProviderCallId: ReturnType<typeof vi.fn>;
19-
};
20-
stop: ReturnType<typeof vi.fn>;
21-
};
10+
let runtimeStub: VoiceCallRuntime;
2211

2312
vi.mock("./runtime-entry.js", () => ({
2413
createVoiceCallRuntime: vi.fn(async () => runtimeStub),
@@ -37,6 +26,7 @@ const noopLogger = {
3726
type Registered = {
3827
methods: Map<string, unknown>;
3928
tools: unknown[];
29+
service?: Parameters<OpenClawPluginApi["registerService"]>[0];
4030
};
4131
type RegisterVoiceCall = (api: Record<string, unknown>) => void;
4232
type RegisterCliContext = {
@@ -57,9 +47,42 @@ function captureStdout() {
5747
restore: () => writeSpy.mockRestore(),
5848
};
5949
}
50+
51+
function createRuntimeStub(callId = "call-1"): VoiceCallRuntime {
52+
return {
53+
config: { toNumber: "+15550001234" } as VoiceCallRuntime["config"],
54+
provider: {} as VoiceCallRuntime["provider"],
55+
manager: {
56+
initiateCall: vi.fn(async () => ({ callId, success: true })),
57+
continueCall: vi.fn(async () => ({
58+
success: true,
59+
transcript: "hello",
60+
})),
61+
speak: vi.fn(async () => ({ success: true })),
62+
sendDtmf: vi.fn(async () => ({ success: true })),
63+
endCall: vi.fn(async () => ({ success: true })),
64+
getCall: vi.fn((id: string) => (id === callId ? { callId } : undefined)),
65+
getCallByProviderCallId: vi.fn(() => undefined),
66+
} as unknown as VoiceCallRuntime["manager"],
67+
webhookServer: {} as VoiceCallRuntime["webhookServer"],
68+
webhookUrl: "http://127.0.0.1:3334/voice/webhook",
69+
publicUrl: null,
70+
stop: vi.fn(async () => {}),
71+
};
72+
}
73+
74+
function createServiceContext(): Parameters<NonNullable<Registered["service"]>["start"]>[0] {
75+
return {
76+
config: {},
77+
stateDir: os.tmpdir(),
78+
logger: noopLogger,
79+
} as Parameters<NonNullable<Registered["service"]>["start"]>[0];
80+
}
81+
6082
function setup(config: Record<string, unknown>): Registered {
6183
const methods = new Map<string, unknown>();
6284
const tools: unknown[] = [];
85+
let service: Registered["service"];
6386
const api = createTestPluginApi({
6487
id: "voice-call",
6588
name: "Voice Call",
@@ -73,11 +96,13 @@ function setup(config: Record<string, unknown>): Registered {
7396
registerGatewayMethod: (method: string, handler: unknown) => methods.set(method, handler),
7497
registerTool: (tool: unknown) => tools.push(tool),
7598
registerCli: () => {},
76-
registerService: () => {},
99+
registerService: (registeredService) => {
100+
service = registeredService;
101+
},
77102
resolvePath: (p: string) => p,
78103
});
79104
plugin.register(api);
80-
return { methods, tools };
105+
return { methods, tools, service };
81106
}
82107

83108
async function registerVoiceCallCli(program: Command) {
@@ -114,26 +139,60 @@ describe("voice-call plugin", () => {
114139
noopLogger.warn.mockClear();
115140
noopLogger.error.mockClear();
116141
noopLogger.debug.mockClear();
117-
vi.mocked(createVoiceCallRuntime).mockClear();
118-
runtimeStub = {
119-
config: { toNumber: "+15550001234" },
120-
manager: {
121-
initiateCall: vi.fn(async () => ({ callId: "call-1", success: true })),
122-
continueCall: vi.fn(async () => ({
123-
success: true,
124-
transcript: "hello",
125-
})),
126-
speak: vi.fn(async () => ({ success: true })),
127-
sendDtmf: vi.fn(async () => ({ success: true })),
128-
endCall: vi.fn(async () => ({ success: true })),
129-
getCall: vi.fn((id: string) => (id === "call-1" ? { callId: "call-1" } : undefined)),
130-
getCallByProviderCallId: vi.fn(() => undefined),
131-
},
132-
stop: vi.fn(async () => {}),
133-
};
142+
runtimeStub = createRuntimeStub();
143+
vi.mocked(createVoiceCallRuntime).mockReset();
144+
vi.mocked(createVoiceCallRuntime).mockImplementation(async () => runtimeStub);
145+
});
146+
147+
afterEach(() => {
148+
vi.restoreAllMocks();
149+
delete (globalThis as Record<PropertyKey, unknown>)[Symbol.for("openclaw.voice-call.runtime")];
150+
delete (globalThis as Record<PropertyKey, unknown>)[
151+
Symbol.for("openclaw.voice-call.runtimePromise")
152+
];
153+
delete (globalThis as Record<PropertyKey, unknown>)[
154+
Symbol.for("openclaw.voice-call.runtimeStopPromise")
155+
];
156+
});
157+
158+
it("reuses a started runtime across plugin registration contexts", async () => {
159+
const first = setup({ provider: "mock" });
160+
const second = setup({ provider: "mock" });
161+
162+
await first.service?.start(createServiceContext());
163+
const handler = second.methods.get("voicecall.initiate") as
164+
| ((ctx: {
165+
params: Record<string, unknown>;
166+
respond: ReturnType<typeof vi.fn>;
167+
}) => Promise<void>)
168+
| undefined;
169+
const respond = vi.fn();
170+
await handler?.({ params: { message: "Hi" }, respond });
171+
172+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
173+
expect(runtimeStub.manager.initiateCall).toHaveBeenCalledTimes(1);
174+
expect(respond).toHaveBeenCalledWith(true, { callId: "call-1", initiated: true });
134175
});
135176

136-
afterEach(() => vi.restoreAllMocks());
177+
it("creates a fresh shared runtime after service stop", async () => {
178+
const first = setup({ provider: "mock" });
179+
await first.service?.start(createServiceContext());
180+
await first.service?.stop?.(createServiceContext());
181+
182+
runtimeStub = createRuntimeStub("call-2");
183+
const second = setup({ provider: "mock" });
184+
const handler = second.methods.get("voicecall.initiate") as
185+
| ((ctx: {
186+
params: Record<string, unknown>;
187+
respond: ReturnType<typeof vi.fn>;
188+
}) => Promise<void>)
189+
| undefined;
190+
const respond = vi.fn();
191+
await handler?.({ params: { message: "Hi" }, respond });
192+
193+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(2);
194+
expect(respond).toHaveBeenCalledWith(true, { callId: "call-2", initiated: true });
195+
});
137196

138197
it("initiates a call via voicecall.initiate", async () => {
139198
const { methods } = setup({ provider: "mock" });

‎extensions/voice-call/index.ts‎

Lines changed: 82 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,24 @@ function asParamRecord(params: unknown): Record<string, unknown> {
154154
: {};
155155
}
156156

157+
const VOICE_CALL_RUNTIME_KEY = Symbol.for("openclaw.voice-call.runtime");
158+
const VOICE_CALL_RUNTIME_PROMISE_KEY = Symbol.for("openclaw.voice-call.runtimePromise");
159+
const VOICE_CALL_RUNTIME_STOP_PROMISE_KEY = Symbol.for("openclaw.voice-call.runtimeStopPromise");
160+
161+
type VoiceCallRuntimeGlobalState = typeof globalThis & {
162+
[VOICE_CALL_RUNTIME_KEY]?: VoiceCallRuntime | null;
163+
[VOICE_CALL_RUNTIME_PROMISE_KEY]?: Promise<VoiceCallRuntime> | null;
164+
[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY]?: Promise<void> | null;
165+
};
166+
167+
function getVoiceCallRuntimeGlobalState(): VoiceCallRuntimeGlobalState {
168+
const state = globalThis as VoiceCallRuntimeGlobalState;
169+
state[VOICE_CALL_RUNTIME_KEY] ??= null;
170+
state[VOICE_CALL_RUNTIME_PROMISE_KEY] ??= null;
171+
state[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY] ??= null;
172+
return state;
173+
}
174+
157175
export default definePluginEntry({
158176
id: "voice-call",
159177
name: "Voice Call",
@@ -173,39 +191,60 @@ export default definePluginEntry({
173191
}
174192
}
175193

176-
let runtimePromise: Promise<VoiceCallRuntime> | null = null;
177-
let runtime: VoiceCallRuntime | null = null;
194+
const runtimeState = getVoiceCallRuntimeGlobalState();
178195

179-
const ensureRuntime = async () => {
196+
const ensureRuntime = async (): Promise<VoiceCallRuntime> => {
180197
if (!config.enabled) {
181198
throw new Error("Voice call disabled in plugin config");
182199
}
183200
if (!validation.valid) {
184201
throw new Error(validation.errors.join("; "));
185202
}
186-
if (runtime) {
187-
return runtime;
188-
}
189-
if (!runtimePromise) {
190-
runtimePromise = createVoiceCallRuntime({
191-
config,
192-
coreConfig: api.config as CoreConfig,
193-
fullConfig: api.config,
194-
agentRuntime: api.runtime.agent,
195-
ttsRuntime: api.runtime.tts,
196-
logger: api.logger,
197-
});
198-
}
199-
try {
200-
runtime = await runtimePromise;
201-
} catch (err) {
202-
// Reset so the next call can retry instead of caching the
203-
// rejected promise forever (which also leaves the port orphaned
204-
// if the server started before the failure). See: #32387
205-
runtimePromise = null;
206-
throw err;
203+
204+
while (true) {
205+
if (runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY]) {
206+
await runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY];
207+
continue;
208+
}
209+
210+
const runtime = runtimeState[VOICE_CALL_RUNTIME_KEY];
211+
if (runtime) {
212+
return runtime;
213+
}
214+
215+
let runtimePromise = runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY];
216+
if (!runtimePromise) {
217+
runtimePromise = createVoiceCallRuntime({
218+
config,
219+
coreConfig: api.config as CoreConfig,
220+
fullConfig: api.config,
221+
agentRuntime: api.runtime.agent,
222+
ttsRuntime: api.runtime.tts,
223+
logger: api.logger,
224+
});
225+
runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY] = runtimePromise;
226+
}
227+
228+
try {
229+
const createdRuntime = await runtimePromise;
230+
if (runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY]) {
231+
continue;
232+
}
233+
if (runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY] !== runtimePromise) {
234+
continue;
235+
}
236+
runtimeState[VOICE_CALL_RUNTIME_KEY] = createdRuntime;
237+
return createdRuntime;
238+
} catch (err) {
239+
if (runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY] === runtimePromise) {
240+
// Reset shared state so the next call can retry instead of caching
241+
// a rejected promise across plugin contexts. See: #32387, #58115.
242+
runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY] = null;
243+
runtimeState[VOICE_CALL_RUNTIME_KEY] = null;
244+
}
245+
throw err;
246+
}
207247
}
208-
return runtime;
209248
};
210249

211250
const sendError = (respond: (ok: boolean, payload?: unknown) => void, err: unknown) => {
@@ -574,15 +613,28 @@ export default definePluginEntry({
574613
}
575614
},
576615
stop: async () => {
577-
if (!runtimePromise) {
616+
if (runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY]) {
617+
await runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY];
578618
return;
579619
}
580-
try {
581-
const rt = await runtimePromise;
620+
const runtime = runtimeState[VOICE_CALL_RUNTIME_KEY];
621+
const runtimePromise = runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY];
622+
if (!runtime && !runtimePromise) {
623+
return;
624+
}
625+
runtimeState[VOICE_CALL_RUNTIME_KEY] = null;
626+
runtimeState[VOICE_CALL_RUNTIME_PROMISE_KEY] = null;
627+
const stopPromise = (async () => {
628+
const rt = runtime ?? (await runtimePromise!);
582629
await rt.stop();
630+
})();
631+
runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY] = stopPromise;
632+
try {
633+
await stopPromise;
583634
} finally {
584-
runtimePromise = null;
585-
runtime = null;
635+
if (runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY] === stopPromise) {
636+
runtimeState[VOICE_CALL_RUNTIME_STOP_PROMISE_KEY] = null;
637+
}
586638
}
587639
},
588640
});

0 commit comments

Comments
 (0)