Skip to content

Commit 75fcaba

Browse files
authored
fix(voice-call): survive gateway in-process restart and stop CLI dead-ends (#125458)
* fix(voice-call): survive gateway in-process restart and stop CLI dead-ends The gateway's in-process restart (SIGUSR1 config reload) reuses the cached plugin registry, so service stop/start run on the same retained voice-call registration. Generation fencing from #120289 treated that restart as a stale actor: stop retired the generation forever, the next start silently bailed, and every voicecall.* RPC answered UNAVAILABLE "runtime generation is retired" while the webhook never rebound. - Registrations now hold a replaceable generation: service start after stop mints a fresh generation, takes over a running slot owned by a retired predecessor, and reports start failures to service health instead of silently returning. - The voicecall CLI classifies gateway failures with typed guards instead of message substrings: standalone/store fallback only when the gateway is genuinely absent; reachable-but-failed (request errors, auth, timeout) exits with actionable text; a standalone webhook port collision explains that a running Gateway probably owns the port instead of raw EADDRINUSE. - Plugin SDK gateway-runtime exports structural isGatewayTransportError / isGatewayClientRequestError guards (+2 documented surface budget). - Regression coverage: same-registration stop/start restart, retired-owner takeover, typed CLI fallback classification, and a real token-auth gateway server routing voicecall.status through callGatewayFromCli. * refactor(voice-call): split CLI modules and dedupe gateway fallbacks Collapse the four duplicated gateway-or-runtime command blocks (speak, dtmf, end, continue fallback) into one generic runGatewayManagerCommand helper — the continue command owns its legacy-method fallback and operation polling via a gatewayCall closure, so the helper carries no per-command policy. Smoke reuses the shared initiateVoiceCall path instead of a bespoke fallback. Split the 988-line cli.ts into concept modules (cli-gateway-call, cli-call-log, cli-command-io) and drop its grandfathered max-lines suppression plus the now-stale max-lines and assertion-safety baseline entries (shrink-only ratchet maintenance). Behavior-frozen: stdout/exit semantics unchanged; net -2 production LOC. * fix(voice-call): redact gateway URLs in CLI operational errors ClawSweeper P1: the operational-error formatter interpolated the raw connectionDetails.url, so a configured gateway URL with userinfo or query tokens would print credentials into terminal output. Redact the composed message once with the canonical net-policy redactor (also covers remote-controlled close-reason text), exported through the plugin SDK gateway-runtime subpath (+1 documented surface budget). Regression test covers a credential-bearing URL in both the URL and message fields.
1 parent b82d07f commit 75fcaba

15 files changed

Lines changed: 1027 additions & 713 deletions

‎config/assertion-safety-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1382,7 +1382,6 @@ extensions/vllm/stream.ts 1
13821382
extensions/voice-call/doctor-contract-api.ts 1
13831383
extensions/voice-call/index.ts 2
13841384
extensions/voice-call/setup-api.ts 1
1385-
extensions/voice-call/src/cli.ts 2
13861385
extensions/voice-call/src/config.ts 2
13871386
extensions/voice-call/src/manager.ts 2
13881387
extensions/voice-call/src/manager/outbound.ts 3

‎config/max-lines-baseline.txt‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,6 @@ extensions/telegram/src/thread-bindings.ts
256256
extensions/telegram/src/webhook.test.ts
257257
extensions/tlon/src/monitor/index.ts
258258
extensions/voice-call/index.test.ts
259-
extensions/voice-call/src/cli.ts
260259
extensions/voice-call/src/media-stream.ts
261260
extensions/voice-call/src/webhook.test.ts
262261
extensions/voice-call/src/webhook.ts

‎docs/cli/voicecall.md‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,15 @@ plugin is installed and enabled.
1414
When the Gateway is running, operational commands (`call`, `start`,
1515
`continue`, `speak`, `dtmf`, `end`, `status`) route to that Gateway's
1616
voice-call runtime. If no Gateway is reachable, they fall back to a standalone
17-
CLI runtime.
17+
CLI runtime. `status` uses the persisted call store instead of starting that
18+
runtime.
19+
20+
Fallback is limited to transport-level absence. If the Gateway responds with a
21+
request or authentication error, or does not answer before the timeout, the
22+
command exits nonzero and points to `openclaw gateway status`; it does not start
23+
a second webhook server. If standalone fallback cannot bind the configured
24+
`serve.port`, the error identifies the likely running Gateway instead of
25+
printing a raw `EADDRINUSE` failure.
1826

1927
## Subcommands
2028

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

Lines changed: 62 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import plugin from "./index.js";
1313
import { createVoiceCallRuntime } from "./runtime-entry.js";
1414

1515
type VoiceCallService = Parameters<OpenClawPluginApi["registerService"]>[0];
16+
type VoiceCallGatewayHandler = Parameters<OpenClawPluginApi["registerGatewayMethod"]>[1];
1617
type VoiceCallTool = {
1718
execute: (toolCallId: string, params: unknown) => Promise<VoiceCallToolResult>;
1819
};
@@ -66,6 +67,7 @@ function registerVoiceCall(params: {
6667
}) {
6768
let service: VoiceCallService | undefined;
6869
let toolFactory: VoiceCallToolFactory | undefined;
70+
const gatewayHandlers = new Map<string, VoiceCallGatewayHandler>();
6971
const api = createTestPluginApi({
7072
id: "voice-call",
7173
name: "Voice Call",
@@ -77,7 +79,9 @@ function registerVoiceCall(params: {
7779
pluginConfig: { provider: "mock", ...params.config },
7880
runtime: { tts: { textToSpeechTelephony: vi.fn() } } as unknown as OpenClawPluginApi["runtime"],
7981
logger: params.logger ?? createLogger(),
80-
registerGatewayMethod: () => {},
82+
registerGatewayMethod: (method, handler) => {
83+
gatewayHandlers.set(method, handler);
84+
},
8185
registerTool: (registration) => {
8286
toolFactory =
8387
typeof registration === "function"
@@ -95,13 +99,27 @@ function registerVoiceCall(params: {
9599
throw new Error("expected voice-call service and tool registrations");
96100
}
97101
const registeredToolFactory = toolFactory;
98-
return { service, toolFactory: registeredToolFactory, tool: () => registeredToolFactory({}) };
102+
return {
103+
gatewayHandlers,
104+
service,
105+
toolFactory: registeredToolFactory,
106+
tool: () => registeredToolFactory({}),
107+
};
99108
}
100109

101110
function executeCall(tool: VoiceCallTool): Promise<VoiceCallToolResult> {
102111
return tool.execute("call", { action: "initiate_call", message: "hello" });
103112
}
104113

114+
async function executeGatewayCall(registration: ReturnType<typeof registerVoiceCall>) {
115+
const respond = vi.fn();
116+
await registration.gatewayHandlers.get("voicecall.initiate")?.({
117+
params: { message: "hello" },
118+
respond,
119+
} as never);
120+
return respond;
121+
}
122+
105123
function expectLifecycleError(result: VoiceCallToolResult, text: string): void {
106124
const detail = result.details?.error;
107125
const error = typeof detail === "string" ? detail : JSON.stringify(detail ?? "");
@@ -162,6 +180,29 @@ describe("voice-call runtime lifecycle", () => {
162180
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
163181
});
164182

183+
it("restarts tools and gateway commands on the same service registration", async () => {
184+
const runtimeA = createRuntime("call-a", "+15550000001");
185+
const runtimeB = createRuntime("call-b", "+15550000002");
186+
vi.mocked(createVoiceCallRuntime)
187+
.mockResolvedValueOnce(runtimeA.runtime)
188+
.mockResolvedValueOnce(runtimeB.runtime);
189+
const registration = registerVoiceCall({});
190+
const retainedTool = registration.tool();
191+
192+
expect(registration.service.start(serviceContext)).toBeUndefined();
193+
await executeCall(retainedTool);
194+
await registration.service.stop?.(serviceContext);
195+
expect(registration.service.start(serviceContext)).toBeUndefined();
196+
197+
await executeCall(retainedTool);
198+
const respond = await executeGatewayCall(registration);
199+
200+
expect(respond).toHaveBeenCalledWith(true, { callId: "call-b", initiated: true });
201+
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(2);
202+
expect(runtimeA.stop).toHaveBeenCalledTimes(1);
203+
expect(runtimeB.initiateCall).toHaveBeenCalledTimes(2);
204+
});
205+
165206
it("waits for A stopping before creating B with B config", async () => {
166207
const aStopEntered = createDeferred<void>();
167208
const releaseAStop = createDeferred<void>();
@@ -242,32 +283,44 @@ describe("voice-call runtime lifecycle", () => {
242283
});
243284

244285
it("does not revive an older staged A after activated B stops", async () => {
286+
const logged = createDeferred<string>();
245287
const runtimeB = createRuntime("call-b", "+15550000002");
246288
vi.mocked(createVoiceCallRuntime).mockResolvedValue(runtimeB.runtime);
247-
const stagedA = registerVoiceCall({ registrationMode: "full" });
289+
const stagedA = registerVoiceCall({
290+
logger: createLogger(logged.resolve),
291+
registrationMode: "full",
292+
});
248293
const retainedToolA = stagedA.tool();
249294
const generationB = registerVoiceCall({ registrationMode: "full" });
250295

251296
await executeCall(generationB.tool());
252297
await generationB.service.stop?.(serviceContext);
253298
expectLifecycleError(await executeCall(retainedToolA), "superseded");
299+
expect(stagedA.service.start(serviceContext)).toBeUndefined();
300+
await expect(logged.promise).resolves.toContain("superseded");
301+
expect(serviceHealth.reportFailure).toHaveBeenCalledWith(
302+
expect.objectContaining({ message: expect.stringContaining("superseded") }),
303+
);
254304

255305
expect(createVoiceCallRuntime).toHaveBeenCalledTimes(1);
256306
expect(runtimeB.stop).toHaveBeenCalledTimes(1);
257307
});
258308

259-
it("logs when successor startup is blocked by an active predecessor", async () => {
260-
const logged = createDeferred<string>();
309+
it("takes over a running slot owned by a retired predecessor", async () => {
261310
const runtimeA = createRuntime("call-a", "+15550000001");
262-
vi.mocked(createVoiceCallRuntime).mockResolvedValue(runtimeA.runtime);
311+
const runtimeB = createRuntime("call-b", "+15550000002");
312+
vi.mocked(createVoiceCallRuntime)
313+
.mockResolvedValueOnce(runtimeA.runtime)
314+
.mockResolvedValueOnce(runtimeB.runtime);
263315
const generationA = registerVoiceCall({});
264316
await executeCall(generationA.tool());
265-
const generationB = registerVoiceCall({ logger: createLogger(logged.resolve) });
317+
const generationB = registerVoiceCall({});
266318

267319
expect(generationB.service.start(serviceContext)).toBeUndefined();
268-
await expect(logged.promise).resolves.toContain("previous voice call runtime generation");
320+
await executeCall(generationB.tool());
269321

270-
await generationA.service.stop?.(serviceContext);
322+
expect(runtimeA.stop).toHaveBeenCalledTimes(1);
323+
expect(runtimeB.initiateCall).toHaveBeenCalledTimes(1);
271324
await generationB.service.stop?.(serviceContext);
272325
});
273326

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

Lines changed: 20 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -187,10 +187,6 @@ function firstRuntimeConfig(): VoiceCallRuntime["config"] | undefined {
187187
return options?.config;
188188
}
189189

190-
function expectWarningIncludes(text: string): void {
191-
expect(noopLogger.warn.mock.calls.map(([message]) => String(message)).join("\n")).toContain(text);
192-
}
193-
194190
function expectRedactedVoiceCallStatus(value: unknown): void {
195191
expect(value).toEqual({
196192
callId: "call-1",
@@ -247,7 +243,13 @@ describe("voice-call plugin", () => {
247243
noopLogger.debug.mockClear();
248244
runtimeStub = createRuntimeStub();
249245
callGatewayFromCliMock.mockReset();
250-
callGatewayFromCliMock.mockRejectedValue(new Error("connect ECONNREFUSED 127.0.0.1:18789"));
246+
callGatewayFromCliMock.mockRejectedValue(
247+
Object.assign(new Error("gateway transport failed"), {
248+
name: "GatewayTransportError",
249+
kind: "closed",
250+
connectionDetails: { url: "ws://127.0.0.1:18789" },
251+
}),
252+
);
251253
vi.mocked(createVoiceCallRuntime).mockReset();
252254
vi.mocked(createVoiceCallRuntime).mockImplementation(async () => runtimeStub);
253255
});
@@ -337,22 +339,26 @@ describe("voice-call plugin", () => {
337339
}
338340
});
339341

340-
it("does not log a startup error when provider setup is incomplete", async () => {
342+
it("reports degraded service health when provider setup is incomplete", async () => {
341343
vi.stubEnv("TWILIO_ACCOUNT_SID", "");
342344
vi.stubEnv("TWILIO_AUTH_TOKEN", "");
343345
vi.stubEnv("TWILIO_FROM_NUMBER", "");
344346
const { service } = setup({ provider: "twilio" });
347+
const reportFailure = vi.fn();
345348

346-
await service?.start(createServiceContext());
349+
await service?.start({
350+
...createServiceContext(),
351+
serviceHealth: { reportFailure, clearFailure: vi.fn() },
352+
});
347353

348354
expect(createVoiceCallRuntime).not.toHaveBeenCalled();
349-
expect(
350-
noopLogger.error.mock.calls.some(([message]) =>
351-
String(message).includes("Failed to start runtime"),
352-
),
353-
).toBe(false);
354-
expectWarningIncludes("Runtime not started; setup incomplete");
355-
expectWarningIncludes("TWILIO_ACCOUNT_SID");
355+
expect(noopLogger.error.mock.calls.flat().join("\n")).toContain(
356+
"Runtime not started: setup incomplete",
357+
);
358+
expect(noopLogger.error.mock.calls.flat().join("\n")).toContain("TWILIO_ACCOUNT_SID");
359+
expect(reportFailure).toHaveBeenCalledWith(
360+
expect.objectContaining({ message: expect.stringContaining("TWILIO_ACCOUNT_SID") }),
361+
);
356362
});
357363

358364
it("registers Twilio configs with SecretRef auth tokens", async () => {

0 commit comments

Comments
 (0)