Skip to content

Commit 32361e7

Browse files
authored
fix(voice-call): isolate runtime generations (#120289)
Prevent retained plugin closures from recreating, adopting, or stopping successor runtimes across shutdown and restart. Add deterministic lifecycle regressions for pending startup, exact-owner stop, retained tools, and generation restart.
1 parent 10e60fa commit 32361e7

3 files changed

Lines changed: 455 additions & 138 deletions

File tree

Lines changed: 282 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,282 @@
1+
import os from "node:os";
2+
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
3+
import { createTestPluginApi } from "openclaw/plugin-sdk/plugin-test-api";
4+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5+
import type { OpenClawPluginApi } from "./api.js";
6+
import type { VoiceCallRuntime } from "./runtime-entry.js";
7+
8+
vi.mock("./runtime-entry.js", () => ({
9+
createVoiceCallRuntime: vi.fn(),
10+
}));
11+
12+
import plugin from "./index.js";
13+
import { createVoiceCallRuntime } from "./runtime-entry.js";
14+
15+
type VoiceCallService = Parameters<OpenClawPluginApi["registerService"]>[0];
16+
type VoiceCallTool = {
17+
execute: (toolCallId: string, params: unknown) => Promise<VoiceCallToolResult>;
18+
};
19+
type VoiceCallToolFactory = (context: Record<string, unknown>) => VoiceCallTool;
20+
type VoiceCallToolResult = {
21+
content?: Array<{ text?: string }>;
22+
details?: { error?: unknown };
23+
};
24+
25+
type RuntimeFixture = {
26+
initiateCall: ReturnType<typeof vi.fn>;
27+
runtime: VoiceCallRuntime;
28+
stop: ReturnType<typeof vi.fn>;
29+
};
30+
31+
const serviceContext = {
32+
config: {},
33+
stateDir: os.tmpdir(),
34+
logger: { info() {}, warn() {}, error() {}, debug() {} },
35+
} as Parameters<VoiceCallService["start"]>[0];
36+
37+
function createLogger(onError?: (message: string) => void) {
38+
return {
39+
info: vi.fn(),
40+
warn: vi.fn(),
41+
error: vi.fn((message: string) => onError?.(message)),
42+
debug: vi.fn(),
43+
};
44+
}
45+
46+
function createRuntime(callId: string, toNumber: string, stopImpl?: () => Promise<void>) {
47+
const initiateCall = vi.fn(async () => ({ callId, success: true }));
48+
const stop = vi.fn(stopImpl ?? (async () => {}));
49+
const runtime = {
50+
config: { toNumber, realtime: { enabled: false } },
51+
manager: { initiateCall },
52+
stop,
53+
} as unknown as VoiceCallRuntime;
54+
return { initiateCall, runtime, stop } satisfies RuntimeFixture;
55+
}
56+
57+
function registerVoiceCall(params: {
58+
config?: Record<string, unknown>;
59+
logger?: ReturnType<typeof createLogger>;
60+
registrationMode?: OpenClawPluginApi["registrationMode"];
61+
}) {
62+
let service: VoiceCallService | undefined;
63+
let toolFactory: VoiceCallToolFactory | undefined;
64+
const api = createTestPluginApi({
65+
id: "voice-call",
66+
name: "Voice Call",
67+
description: "test",
68+
version: "0",
69+
source: "test",
70+
registrationMode: params.registrationMode ?? "full",
71+
config: {},
72+
pluginConfig: { provider: "mock", ...params.config },
73+
runtime: { tts: { textToSpeechTelephony: vi.fn() } } as unknown as OpenClawPluginApi["runtime"],
74+
logger: params.logger ?? createLogger(),
75+
registerGatewayMethod: () => {},
76+
registerTool: (registration) => {
77+
toolFactory =
78+
typeof registration === "function"
79+
? (registration as unknown as VoiceCallToolFactory)
80+
: () => registration as unknown as VoiceCallTool;
81+
},
82+
registerCli: () => {},
83+
registerService: (registeredService) => {
84+
service = registeredService;
85+
},
86+
resolvePath: (value) => value,
87+
});
88+
plugin.register(api);
89+
if (!service || !toolFactory) {
90+
throw new Error("expected voice-call service and tool registrations");
91+
}
92+
const registeredToolFactory = toolFactory;
93+
return { service, toolFactory: registeredToolFactory, tool: () => registeredToolFactory({}) };
94+
}
95+
96+
function executeCall(tool: VoiceCallTool): Promise<VoiceCallToolResult> {
97+
return tool.execute("call", { action: "initiate_call", message: "hello" });
98+
}
99+
100+
function expectLifecycleError(result: VoiceCallToolResult, text: string): void {
101+
const detail = result.details?.error;
102+
const error = typeof detail === "string" ? detail : JSON.stringify(detail ?? "");
103+
expect(error).toContain(text);
104+
expect(result.content?.some((entry) => entry.text?.includes(error))).toBe(true);
105+
}
106+
107+
describe("voice-call runtime lifecycle", () => {
108+
beforeEach(() => {
109+
vi.mocked(createVoiceCallRuntime).mockReset();
110+
});
111+
112+
afterEach(() => {
113+
delete (globalThis as Record<PropertyKey, unknown>)[
114+
Symbol.for("openclaw.voice-call.runtimeCoordinator")
115+
];
116+
vi.restoreAllMocks();
117+
});
118+
119+
it("shares one pending runtime between full and tool-discovery registrations", async () => {
120+
const runtimeReady = createDeferred<VoiceCallRuntime>();
121+
const fixture = createRuntime("call-a", "+15550000001");
122+
vi.mocked(createVoiceCallRuntime).mockReturnValue(runtimeReady.promise);
123+
const full = registerVoiceCall({ registrationMode: "full" });
124+
125+
expect(full.service.start(serviceContext)).toBeUndefined();
126+
const discovery = registerVoiceCall({ registrationMode: "tool-discovery" });
127+
const fullCall = executeCall(full.tool());
128+
const discoveryCall = executeCall(discovery.tool());
129+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
130+
131+
runtimeReady.resolve(fixture.runtime);
132+
await Promise.all([fullCall, discoveryCall]);
133+
134+
expect(fixture.initiateCall).toHaveBeenCalledTimes(2);
135+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
136+
});
137+
138+
it("retires a pending generation and stops its late runtime once", async () => {
139+
const runtimeReady = createDeferred<VoiceCallRuntime>();
140+
const fixture = createRuntime("call-a", "+15550000001");
141+
const logger = createLogger();
142+
vi.mocked(createVoiceCallRuntime).mockReturnValue(runtimeReady.promise);
143+
const generationA = registerVoiceCall({ logger });
144+
145+
expect(generationA.service.start(serviceContext)).toBeUndefined();
146+
const firstStop = generationA.service.stop?.(serviceContext);
147+
const secondStop = generationA.service.stop?.(serviceContext);
148+
runtimeReady.resolve(fixture.runtime);
149+
await Promise.all([firstStop, secondStop]);
150+
151+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
152+
expect(fixture.stop).toHaveBeenCalledTimes(1);
153+
expect(logger.error).not.toHaveBeenCalled();
154+
expectLifecycleError(await executeCall(generationA.tool()), "retired");
155+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
156+
});
157+
158+
it("waits for A stopping before creating B with B config", async () => {
159+
const aStopEntered = createDeferred<void>();
160+
const releaseAStop = createDeferred<void>();
161+
const runtimeA = createRuntime("call-a", "+15550000001", () => {
162+
aStopEntered.resolve();
163+
return releaseAStop.promise;
164+
});
165+
const runtimeB = createRuntime("call-b", "+15550000002");
166+
vi.mocked(createVoiceCallRuntime)
167+
.mockResolvedValueOnce(runtimeA.runtime)
168+
.mockResolvedValueOnce(runtimeB.runtime);
169+
const generationA = registerVoiceCall({ config: { toNumber: "+15550000001" } });
170+
await executeCall(generationA.tool());
171+
const generationB = registerVoiceCall({ config: { toNumber: "+15550000002" } });
172+
173+
const stoppingA = generationA.service.stop?.(serviceContext);
174+
const callB = executeCall(generationB.tool());
175+
await aStopEntered.promise;
176+
expect(runtimeA.stop).toHaveBeenCalledTimes(1);
177+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
178+
179+
releaseAStop.resolve();
180+
await Promise.all([stoppingA, callB]);
181+
182+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(2);
183+
expect(vi.mocked(createVoiceCallRuntime).mock.calls[1]?.[0].config.toNumber).toBe(
184+
"+15550000002",
185+
);
186+
expect(runtimeB.initiateCall).toHaveBeenCalledTimes(1);
187+
});
188+
189+
it("does not let a stale A stop clear or stop running B", async () => {
190+
const runtimeB = createRuntime("call-b", "+15550000002");
191+
vi.mocked(createVoiceCallRuntime).mockResolvedValue(runtimeB.runtime);
192+
const generationA = registerVoiceCall({ config: { toNumber: "+15550000001" } });
193+
const generationB = registerVoiceCall({ config: { toNumber: "+15550000002" } });
194+
195+
await executeCall(generationB.tool());
196+
await generationA.service.stop?.(serviceContext);
197+
await executeCall(generationB.tool());
198+
199+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
200+
expect(runtimeB.initiateCall).toHaveBeenCalledTimes(2);
201+
expect(runtimeB.stop).not.toHaveBeenCalled();
202+
});
203+
204+
it("rejects retained concrete and cold-registry A tools once B activates", async () => {
205+
const runtimeA = createRuntime("call-a", "+15550000001");
206+
const runtimeB = createRuntime("call-b", "+15550000002");
207+
vi.mocked(createVoiceCallRuntime)
208+
.mockResolvedValueOnce(runtimeA.runtime)
209+
.mockResolvedValueOnce(runtimeB.runtime);
210+
const generationA = registerVoiceCall({ registrationMode: "full" });
211+
const concreteToolA = generationA.tool();
212+
await executeCall(concreteToolA);
213+
const coldRegistryA = registerVoiceCall({ registrationMode: "tool-discovery" });
214+
const coldToolA = coldRegistryA.toolFactory({});
215+
const generationB = registerVoiceCall({ registrationMode: "full" });
216+
217+
await executeCall(concreteToolA);
218+
await executeCall(coldToolA);
219+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
220+
expect(runtimeA.initiateCall).toHaveBeenCalledTimes(3);
221+
222+
expect(generationB.service.start(serviceContext)).toBeUndefined();
223+
expectLifecycleError(await executeCall(concreteToolA), "superseded");
224+
expectLifecycleError(await executeCall(coldToolA), "superseded");
225+
await generationA.service.stop?.(serviceContext);
226+
await executeCall(generationB.tool());
227+
await generationB.service.stop?.(serviceContext);
228+
expectLifecycleError(await executeCall(concreteToolA), "superseded");
229+
expectLifecycleError(await executeCall(coldToolA), "superseded");
230+
231+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(2);
232+
expect(runtimeA.stop).toHaveBeenCalledTimes(1);
233+
expect(runtimeB.initiateCall).toHaveBeenCalledTimes(1);
234+
expect(runtimeB.stop).toHaveBeenCalledTimes(1);
235+
});
236+
237+
it("does not revive an older staged A after activated B stops", async () => {
238+
const runtimeB = createRuntime("call-b", "+15550000002");
239+
vi.mocked(createVoiceCallRuntime).mockResolvedValue(runtimeB.runtime);
240+
const stagedA = registerVoiceCall({ registrationMode: "full" });
241+
const retainedToolA = stagedA.tool();
242+
const generationB = registerVoiceCall({ registrationMode: "full" });
243+
244+
await executeCall(generationB.tool());
245+
await generationB.service.stop?.(serviceContext);
246+
expectLifecycleError(await executeCall(retainedToolA), "superseded");
247+
248+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
249+
expect(runtimeB.stop).toHaveBeenCalledTimes(1);
250+
});
251+
252+
it("logs when successor startup is blocked by an active predecessor", async () => {
253+
const logged = createDeferred<string>();
254+
const runtimeA = createRuntime("call-a", "+15550000001");
255+
vi.mocked(createVoiceCallRuntime).mockResolvedValue(runtimeA.runtime);
256+
const generationA = registerVoiceCall({});
257+
await executeCall(generationA.tool());
258+
const generationB = registerVoiceCall({ logger: createLogger(logged.resolve) });
259+
260+
expect(generationB.service.start(serviceContext)).toBeUndefined();
261+
await expect(logged.promise).resolves.toContain("previous voice call runtime generation");
262+
263+
await generationA.service.stop?.(serviceContext);
264+
await generationB.service.stop?.(serviceContext);
265+
});
266+
267+
it("logs a genuine startup failure and retries the same generation", async () => {
268+
const logged = createDeferred<string>();
269+
const runtimeA = createRuntime("call-a", "+15550000001");
270+
vi.mocked(createVoiceCallRuntime)
271+
.mockRejectedValueOnce(new Error("provider boom"))
272+
.mockResolvedValueOnce(runtimeA.runtime);
273+
const generationA = registerVoiceCall({ logger: createLogger(logged.resolve) });
274+
275+
expect(generationA.service.start(serviceContext)).toBeUndefined();
276+
await expect(logged.promise).resolves.toContain("Failed to start runtime: provider boom");
277+
278+
await executeCall(generationA.tool());
279+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(2);
280+
expect(runtimeA.initiateCall).toHaveBeenCalledTimes(1);
281+
});
282+
});

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

Lines changed: 3 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ function setup(
139139
description: "test",
140140
version: "0",
141141
source: "test",
142+
registrationMode: "full",
142143
config: {},
143144
pluginConfig: config,
144145
runtime: { tts: { textToSpeechTelephony: vi.fn() } } as unknown as OpenClawPluginApi["runtime"],
@@ -219,6 +220,7 @@ async function registerVoiceCallCli(
219220
description: "test",
220221
version: "0",
221222
source: "test",
223+
registrationMode: "full",
222224
config: {},
223225
pluginConfig,
224226
runtime: { tts: { textToSpeechTelephony: vi.fn() } },
@@ -253,12 +255,8 @@ describe("voice-call plugin", () => {
253255
afterEach(() => {
254256
vi.restoreAllMocks();
255257
vi.unstubAllEnvs();
256-
delete (globalThis as Record<PropertyKey, unknown>)[Symbol.for("openclaw.voice-call.runtime")];
257258
delete (globalThis as Record<PropertyKey, unknown>)[
258-
Symbol.for("openclaw.voice-call.runtimePromise")
259-
];
260-
delete (globalThis as Record<PropertyKey, unknown>)[
261-
Symbol.for("openclaw.voice-call.runtimeStopPromise")
259+
Symbol.for("openclaw.voice-call.runtimeCoordinator")
262260
];
263261
});
264262

@@ -289,53 +287,6 @@ describe("voice-call plugin", () => {
289287
expect(createVoiceCallRuntime).not.toHaveBeenCalled();
290288
});
291289

292-
it("reuses a started runtime across plugin registration contexts", async () => {
293-
const first = setup({ provider: "mock" });
294-
const second = setup({ provider: "mock" });
295-
296-
await first.service?.start(createServiceContext());
297-
const handler = second.methods.get("voicecall.initiate") as
298-
| ((ctx: {
299-
params: Record<string, unknown>;
300-
respond: ReturnType<typeof vi.fn>;
301-
}) => Promise<void>)
302-
| undefined;
303-
const respond = vi.fn();
304-
await handler?.({ params: { message: "Hi" }, respond });
305-
306-
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
307-
expect(runtimeStub.manager["initiateCall"]).toHaveBeenCalledTimes(1);
308-
expect(respond).toHaveBeenCalledWith(true, { callId: "call-1", initiated: true });
309-
});
310-
311-
it("does not block service startup while runtime exposure initializes", async () => {
312-
let resolveRuntime: ((runtime: VoiceCallRuntime) => void) | undefined;
313-
vi.mocked(createVoiceCallRuntime).mockReturnValueOnce(
314-
new Promise<VoiceCallRuntime>((resolve) => {
315-
resolveRuntime = resolve;
316-
}),
317-
);
318-
const { service, methods } = setup({ provider: "mock" });
319-
320-
if (!service) {
321-
throw new Error("expected voice-call service");
322-
}
323-
expect(service.start(createServiceContext())).toBeUndefined();
324-
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
325-
326-
resolveRuntime?.(runtimeStub);
327-
const handler = methods.get("voicecall.initiate") as
328-
| ((ctx: {
329-
params: Record<string, unknown>;
330-
respond: ReturnType<typeof vi.fn>;
331-
}) => Promise<void>)
332-
| undefined;
333-
const respond = vi.fn();
334-
await handler?.({ params: { message: "Hi" }, respond });
335-
336-
expect(respond).toHaveBeenCalledWith(true, { callId: "call-1", initiated: true });
337-
});
338-
339290
it("does not start the webhook runtime for CLI-only plugin loading", async () => {
340291
vi.stubEnv("OPENCLAW_CLI", "1");
341292
const { service } = setup({ provider: "mock" });
@@ -359,26 +310,6 @@ describe("voice-call plugin", () => {
359310
}
360311
});
361312

362-
it("creates a fresh shared runtime after service stop", async () => {
363-
const first = setup({ provider: "mock" });
364-
await first.service?.start(createServiceContext());
365-
await first.service?.stop?.(createServiceContext());
366-
367-
runtimeStub = createRuntimeStub("call-2");
368-
const second = setup({ provider: "mock" });
369-
const handler = second.methods.get("voicecall.initiate") as
370-
| ((ctx: {
371-
params: Record<string, unknown>;
372-
respond: ReturnType<typeof vi.fn>;
373-
}) => Promise<void>)
374-
| undefined;
375-
const respond = vi.fn();
376-
await handler?.({ params: { message: "Hi" }, respond });
377-
378-
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(2);
379-
expect(respond).toHaveBeenCalledWith(true, { callId: "call-2", initiated: true });
380-
});
381-
382313
it("does not log a startup error when provider setup is incomplete", async () => {
383314
vi.stubEnv("TWILIO_ACCOUNT_SID", "");
384315
vi.stubEnv("TWILIO_AUTH_TOKEN", "");

0 commit comments

Comments
 (0)