|
1 | | -import type { RealtimeVoiceBridge } from "openclaw/plugin-sdk/realtime-voice"; |
| 1 | +import type { |
| 2 | + RealtimeVoiceBridge, |
| 3 | + RealtimeVoiceProviderPlugin, |
| 4 | +} from "openclaw/plugin-sdk/realtime-voice"; |
2 | 5 | import { describe, expect, it, vi } from "vitest"; |
3 | 6 | import type { WebSocket as WebSocketType } from "ws"; |
4 | 7 | import { WebSocket } from "ws"; |
@@ -52,7 +55,217 @@ function createBridge( |
52 | 55 | }; |
53 | 56 | } |
54 | 57 |
|
| 58 | +function createCarrierLifecycleHarness( |
| 59 | + createBridgeForCall: RealtimeVoiceProviderPlugin["createBridge"], |
| 60 | +) { |
| 61 | + const call: CallRecord = { |
| 62 | + callId: "call-startup", |
| 63 | + providerCallId: "CA-startup", |
| 64 | + provider: "twilio", |
| 65 | + direction: "inbound", |
| 66 | + state: "ringing", |
| 67 | + from: "+15550001111", |
| 68 | + to: "+15550002222", |
| 69 | + startedAt: Date.now(), |
| 70 | + transcript: [], |
| 71 | + processedEventIds: [], |
| 72 | + }; |
| 73 | + const processEvent = vi.fn(); |
| 74 | + const hangupCall = vi.fn(async () => {}); |
| 75 | + const handler = new RealtimeCallHandler( |
| 76 | + createRealtimeConfig(), |
| 77 | + { |
| 78 | + processEvent, |
| 79 | + getCallByProviderCallId: vi.fn(() => call), |
| 80 | + } as unknown as CallManager, |
| 81 | + { name: "twilio", hangupCall } as unknown as VoiceCallProvider, |
| 82 | + { |
| 83 | + id: "openai", |
| 84 | + label: "OpenAI", |
| 85 | + isConfigured: () => true, |
| 86 | + createBridge: createBridgeForCall, |
| 87 | + }, |
| 88 | + { apiKey: "test-key" }, |
| 89 | + "/voice/webhook", |
| 90 | + ); |
| 91 | + return { call, handler, hangupCall, processEvent }; |
| 92 | +} |
| 93 | + |
| 94 | +async function connectCarrierStream(handler: RealtimeCallHandler) { |
| 95 | + const { streamUrl } = handler.issueStreamSession(); |
| 96 | + const server = await startUpgradeWsServer({ |
| 97 | + urlPath: new URL(streamUrl).pathname, |
| 98 | + onUpgrade: (request, socket, head) => { |
| 99 | + handler.handleWebSocketUpgrade(request, socket, head); |
| 100 | + }, |
| 101 | + }); |
| 102 | + return { server, ws: await connectWs(server.url) }; |
| 103 | +} |
| 104 | + |
55 | 105 | describe("RealtimeCallHandler lifecycle", () => { |
| 106 | + it.each([ |
| 107 | + { closeOutcome: undefined, closeReason: "Failed to connect" }, |
| 108 | + { closeOutcome: "completed" as const, closeReason: "Failed to connect" }, |
| 109 | + { closeOutcome: "error" as const, closeReason: "Bridge disconnected" }, |
| 110 | + { closeOutcome: "throws" as const, closeReason: "Failed to connect" }, |
| 111 | + ])( |
| 112 | + "hangs up a rejected startup exactly once when provider close is $closeOutcome", |
| 113 | + async ({ closeOutcome, closeReason }) => { |
| 114 | + let onProviderClose: ((reason: "completed" | "error") => void) | undefined; |
| 115 | + const closeBridge = vi.fn(() => { |
| 116 | + if (closeOutcome === "throws") { |
| 117 | + throw new Error("realtime provider close failed"); |
| 118 | + } |
| 119 | + if (closeOutcome) { |
| 120 | + onProviderClose?.(closeOutcome); |
| 121 | + } |
| 122 | + }); |
| 123 | + const { call, handler, hangupCall, processEvent } = createCarrierLifecycleHarness( |
| 124 | + (request) => { |
| 125 | + onProviderClose = request.onClose; |
| 126 | + return createBridge(closeBridge, { |
| 127 | + connect: async () => { |
| 128 | + throw new Error("realtime provider rejected startup"); |
| 129 | + }, |
| 130 | + }); |
| 131 | + }, |
| 132 | + ); |
| 133 | + const { server, ws } = await connectCarrierStream(handler); |
| 134 | + |
| 135 | + try { |
| 136 | + const closed = waitForClose(ws); |
| 137 | + ws.send( |
| 138 | + JSON.stringify({ |
| 139 | + event: "start", |
| 140 | + start: { streamSid: "MZ-startup", callSid: call.providerCallId }, |
| 141 | + }), |
| 142 | + ); |
| 143 | + |
| 144 | + expect(await closed).toEqual({ code: 1011, reason: closeReason }); |
| 145 | + expect(closeBridge).toHaveBeenCalledTimes(1); |
| 146 | + expect(hangupCall).toHaveBeenCalledExactlyOnceWith({ |
| 147 | + callId: call.callId, |
| 148 | + providerCallId: call.providerCallId, |
| 149 | + reason: "error", |
| 150 | + }); |
| 151 | + const endedEvents = processEvent.mock.calls.filter( |
| 152 | + ([event]) => event.type === "call.ended", |
| 153 | + ); |
| 154 | + expect(endedEvents).toHaveLength(1); |
| 155 | + expect(endedEvents[0]?.[0]).toEqual( |
| 156 | + expect.objectContaining({ |
| 157 | + callId: call.callId, |
| 158 | + providerCallId: call.providerCallId, |
| 159 | + reason: "error", |
| 160 | + }), |
| 161 | + ); |
| 162 | + expect(handler.speak(call.callId, "still connected")).toEqual({ |
| 163 | + success: false, |
| 164 | + error: "No active realtime bridge for call", |
| 165 | + }); |
| 166 | + } finally { |
| 167 | + if (ws.readyState !== WebSocket.CLOSED) { |
| 168 | + ws.terminate(); |
| 169 | + } |
| 170 | + await handler.close(); |
| 171 | + await server.close(); |
| 172 | + } |
| 173 | + }, |
| 174 | + ); |
| 175 | + |
| 176 | + it("hangs up the carrier when its initial realtime bridge cannot be created", async () => { |
| 177 | + const { call, handler, hangupCall, processEvent } = createCarrierLifecycleHarness(() => { |
| 178 | + throw new Error("realtime provider rejected call configuration"); |
| 179 | + }); |
| 180 | + const { server, ws } = await connectCarrierStream(handler); |
| 181 | + |
| 182 | + try { |
| 183 | + const closed = waitForClose(ws); |
| 184 | + ws.send( |
| 185 | + JSON.stringify({ |
| 186 | + event: "start", |
| 187 | + start: { streamSid: "MZ-initial-creation", callSid: call.providerCallId }, |
| 188 | + }), |
| 189 | + ); |
| 190 | + |
| 191 | + expect(await closed).toEqual({ code: 1011, reason: "Failed to create realtime bridge" }); |
| 192 | + expect(hangupCall).toHaveBeenCalledExactlyOnceWith({ |
| 193 | + callId: call.callId, |
| 194 | + providerCallId: call.providerCallId, |
| 195 | + reason: "error", |
| 196 | + }); |
| 197 | + expect(processEvent.mock.calls.filter(([event]) => event.type === "call.ended")).toHaveLength( |
| 198 | + 1, |
| 199 | + ); |
| 200 | + } finally { |
| 201 | + if (ws.readyState !== WebSocket.CLOSED) { |
| 202 | + ws.terminate(); |
| 203 | + } |
| 204 | + await handler.close(); |
| 205 | + await server.close(); |
| 206 | + } |
| 207 | + }); |
| 208 | + |
| 209 | + it("does not hang up a replacement when its stale predecessor rejects startup", async () => { |
| 210 | + let rejectStartup: (error: Error) => void = () => {}; |
| 211 | + const pendingStartup = new Promise<void>((_resolve, reject) => { |
| 212 | + rejectStartup = reject; |
| 213 | + }); |
| 214 | + const replacementGreeting = vi.fn(); |
| 215 | + const createBridgeForCall = vi |
| 216 | + .fn<RealtimeVoiceProviderPlugin["createBridge"]>() |
| 217 | + .mockImplementationOnce(() => createBridge(vi.fn(), { connect: () => pendingStartup })) |
| 218 | + .mockImplementationOnce(() => |
| 219 | + createBridge(vi.fn(), { triggerGreeting: replacementGreeting }), |
| 220 | + ); |
| 221 | + const { call, handler, hangupCall, processEvent } = |
| 222 | + createCarrierLifecycleHarness(createBridgeForCall); |
| 223 | + const previous = await connectCarrierStream(handler); |
| 224 | + let replacement: Awaited<ReturnType<typeof connectCarrierStream>> | undefined; |
| 225 | + |
| 226 | + try { |
| 227 | + previous.ws.send( |
| 228 | + JSON.stringify({ |
| 229 | + event: "start", |
| 230 | + start: { streamSid: "MZ-previous", callSid: call.providerCallId }, |
| 231 | + }), |
| 232 | + ); |
| 233 | + await vi.waitFor(() => expect(createBridgeForCall).toHaveBeenCalledTimes(1)); |
| 234 | + |
| 235 | + replacement = await connectCarrierStream(handler); |
| 236 | + replacement.ws.send( |
| 237 | + JSON.stringify({ |
| 238 | + event: "start", |
| 239 | + start: { streamSid: "MZ-replacement", callSid: call.providerCallId }, |
| 240 | + }), |
| 241 | + ); |
| 242 | + await vi.waitFor(() => expect(createBridgeForCall).toHaveBeenCalledTimes(2)); |
| 243 | + |
| 244 | + const previousClosed = waitForClose(previous.ws); |
| 245 | + rejectStartup(new Error("superseded provider rejected startup")); |
| 246 | + expect(await previousClosed).toEqual({ code: 1011, reason: "Failed to connect" }); |
| 247 | + expect(hangupCall).not.toHaveBeenCalled(); |
| 248 | + expect(processEvent.mock.calls.filter(([event]) => event.type === "call.ended")).toHaveLength( |
| 249 | + 0, |
| 250 | + ); |
| 251 | + expect(replacement.ws.readyState).toBe(WebSocket.OPEN); |
| 252 | + expect(handler.speak(call.callId, "replacement remains connected")).toEqual({ |
| 253 | + success: true, |
| 254 | + }); |
| 255 | + expect(replacementGreeting).toHaveBeenCalledWith("replacement remains connected"); |
| 256 | + } finally { |
| 257 | + if (previous.ws.readyState !== WebSocket.CLOSED) { |
| 258 | + previous.ws.terminate(); |
| 259 | + } |
| 260 | + if (replacement?.ws.readyState !== WebSocket.CLOSED) { |
| 261 | + replacement?.ws.terminate(); |
| 262 | + } |
| 263 | + await handler.close(); |
| 264 | + await replacement?.server.close(); |
| 265 | + await previous.server.close(); |
| 266 | + } |
| 267 | + }); |
| 268 | + |
56 | 269 | it("terminates active sockets and treats server shutdown as completed", async () => { |
57 | 270 | const bridgeClose = vi.fn(); |
58 | 271 | const createBridgeForCall = vi.fn(() => createBridge(bridgeClose)); |
|
0 commit comments