|
| 1 | +import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts"; |
| 2 | +import type { OpenKeyedStoreOptions } from "openclaw/plugin-sdk/plugin-state-runtime"; |
| 3 | +import { |
| 4 | + createPluginStateSyncKeyedStoreForTests, |
| 5 | + resetPluginStateStoreForTests, |
| 6 | +} from "openclaw/plugin-sdk/plugin-state-test-runtime"; |
| 7 | +import type { |
| 8 | + RealtimeVoiceBridge, |
| 9 | + RealtimeVoiceProviderPlugin, |
| 10 | +} from "openclaw/plugin-sdk/realtime-voice"; |
| 11 | +import { useAutoCleanupTempDirTracker } from "openclaw/plugin-sdk/test-env"; |
| 12 | +import { afterEach, describe, expect, it, vi } from "vitest"; |
| 13 | +import { WebSocket } from "ws"; |
| 14 | +import type { VoiceCallStateRuntime } from "./runtime-state.js"; |
| 15 | +import { createVoiceCallRuntime, type VoiceCallRuntime } from "./runtime.js"; |
| 16 | +import { createVoiceCallBaseConfig } from "./test-fixtures.js"; |
| 17 | +import { connectWs, startUpgradeWsServer, waitForClose } from "./websocket-test-support.js"; |
| 18 | + |
| 19 | +const mocks = vi.hoisted(() => ({ |
| 20 | + resolveConfiguredRealtimeVoiceProvider: vi.fn(), |
| 21 | +})); |
| 22 | + |
| 23 | +vi.mock("./realtime-voice.runtime.js", async (importOriginal) => { |
| 24 | + const actual = await importOriginal<typeof import("./realtime-voice.runtime.js")>(); |
| 25 | + return { |
| 26 | + ...actual, |
| 27 | + resolveConfiguredRealtimeVoiceProvider: mocks.resolveConfiguredRealtimeVoiceProvider, |
| 28 | + }; |
| 29 | +}); |
| 30 | + |
| 31 | +function createStateRuntime(): VoiceCallStateRuntime["state"] { |
| 32 | + return { |
| 33 | + resolveStateDir: () => "", |
| 34 | + openKeyedStore: (() => { |
| 35 | + throw new Error("openKeyedStore is not used by realtime routing tests"); |
| 36 | + }) as VoiceCallStateRuntime["state"]["openKeyedStore"], |
| 37 | + openSyncKeyedStore: <T>(options: OpenKeyedStoreOptions) => |
| 38 | + createPluginStateSyncKeyedStoreForTests<T>("voice-call", options), |
| 39 | + openChannelIngressQueue: (() => { |
| 40 | + throw new Error("openChannelIngressQueue is not used by realtime routing tests"); |
| 41 | + }) as VoiceCallStateRuntime["state"]["openChannelIngressQueue"], |
| 42 | + openChannelIngressDrain: (() => { |
| 43 | + throw new Error("openChannelIngressDrain is not used by realtime routing tests"); |
| 44 | + }) as VoiceCallStateRuntime["state"]["openChannelIngressDrain"], |
| 45 | + }; |
| 46 | +} |
| 47 | + |
| 48 | +function createRealtimeProvider(params: { |
| 49 | + id: string; |
| 50 | + connect: ReturnType<typeof vi.fn<() => Promise<void>>>; |
| 51 | +}): RealtimeVoiceProviderPlugin { |
| 52 | + return { |
| 53 | + id: params.id, |
| 54 | + label: params.id, |
| 55 | + isConfigured: () => true, |
| 56 | + createBridge: vi.fn( |
| 57 | + (): RealtimeVoiceBridge => ({ |
| 58 | + connect: params.connect, |
| 59 | + sendAudio: vi.fn(), |
| 60 | + setMediaTimestamp: vi.fn(), |
| 61 | + submitToolResult: vi.fn(), |
| 62 | + acknowledgeMark: vi.fn(), |
| 63 | + close: vi.fn(), |
| 64 | + isConnected: () => true, |
| 65 | + triggerGreeting: vi.fn(), |
| 66 | + }), |
| 67 | + ), |
| 68 | + }; |
| 69 | +} |
| 70 | + |
| 71 | +const tempDirs = useAutoCleanupTempDirTracker(afterEach); |
| 72 | + |
| 73 | +afterEach(() => { |
| 74 | + mocks.resolveConfiguredRealtimeVoiceProvider.mockReset(); |
| 75 | + resetPluginStateStoreForTests(); |
| 76 | +}); |
| 77 | + |
| 78 | +describe("voice-call realtime route ownership", () => { |
| 79 | + it("selects provider readiness and bridge auth from each inbound number owner", async () => { |
| 80 | + const storePath = tempDirs.make("openclaw-voice-routing-"); |
| 81 | + const sockets: WebSocket[] = []; |
| 82 | + const servers: Array<Awaited<ReturnType<typeof startUpgradeWsServer>>> = []; |
| 83 | + let runtime: VoiceCallRuntime | undefined; |
| 84 | + const salesConnect = vi.fn(async () => {}); |
| 85 | + const supportConnect = vi.fn(async () => {}); |
| 86 | + const salesProvider = createRealtimeProvider({ id: "openai", connect: salesConnect }); |
| 87 | + const supportProvider = createRealtimeProvider({ id: "xai", connect: supportConnect }); |
| 88 | + const registrations = new Map([ |
| 89 | + [ |
| 90 | + "sales", |
| 91 | + { |
| 92 | + provider: salesProvider, |
| 93 | + providerConfig: { credentialOwner: "sales", model: "gpt-realtime" }, |
| 94 | + }, |
| 95 | + ], |
| 96 | + [ |
| 97 | + "support", |
| 98 | + { |
| 99 | + provider: supportProvider, |
| 100 | + providerConfig: { credentialOwner: "support", model: "grok-voice" }, |
| 101 | + }, |
| 102 | + ], |
| 103 | + ]); |
| 104 | + mocks.resolveConfiguredRealtimeVoiceProvider.mockImplementation( |
| 105 | + ({ agentId }: { agentId?: string }) => { |
| 106 | + const registration = agentId ? registrations.get(agentId) : undefined; |
| 107 | + if (!registration) { |
| 108 | + throw new Error(`No simulated realtime credentials for ${agentId ?? "unknown"}`); |
| 109 | + } |
| 110 | + return registration; |
| 111 | + }, |
| 112 | + ); |
| 113 | + |
| 114 | + try { |
| 115 | + const config = createVoiceCallBaseConfig(); |
| 116 | + config.agentId = "main"; |
| 117 | + config.store = storePath; |
| 118 | + config.inboundPolicy = "open"; |
| 119 | + config.maxConcurrentCalls = 2; |
| 120 | + config.staleCallReaperSeconds = 0; |
| 121 | + config.serve = { ...config.serve, port: 0 }; |
| 122 | + config.realtime.enabled = true; |
| 123 | + config.numbers = { |
| 124 | + "+15550001001": { agentId: "sales" }, |
| 125 | + "+15550001002": { agentId: "support" }, |
| 126 | + }; |
| 127 | + const fullConfig = { |
| 128 | + agents: { |
| 129 | + list: [{ id: "main", default: true }, { id: "sales" }, { id: "support" }], |
| 130 | + }, |
| 131 | + } as OpenClawConfig; |
| 132 | + |
| 133 | + runtime = await createVoiceCallRuntime({ |
| 134 | + config, |
| 135 | + coreConfig: fullConfig, |
| 136 | + fullConfig, |
| 137 | + agentRuntime: {} as never, |
| 138 | + stateRuntime: createStateRuntime(), |
| 139 | + }); |
| 140 | + expect(mocks.resolveConfiguredRealtimeVoiceProvider).not.toHaveBeenCalled(); |
| 141 | + |
| 142 | + const handler = runtime.webhookServer.getRealtimeHandler(); |
| 143 | + if (!handler) { |
| 144 | + throw new Error("expected realtime handler"); |
| 145 | + } |
| 146 | + const routes = [ |
| 147 | + { to: "+15550001001", callSid: "CA-sales", streamSid: "MZ-sales" }, |
| 148 | + { to: "+15550001002", callSid: "CA-support", streamSid: "MZ-support" }, |
| 149 | + ]; |
| 150 | + for (const route of routes) { |
| 151 | + const { streamUrl } = handler.issueStreamSession({ |
| 152 | + providerName: "twilio", |
| 153 | + direction: "inbound", |
| 154 | + from: "+15550009999", |
| 155 | + to: route.to, |
| 156 | + }); |
| 157 | + const server = await startUpgradeWsServer({ |
| 158 | + urlPath: new URL(streamUrl).pathname, |
| 159 | + onUpgrade: (request, socket, head) => { |
| 160 | + handler.handleWebSocketUpgrade(request, socket, head); |
| 161 | + }, |
| 162 | + }); |
| 163 | + servers.push(server); |
| 164 | + const ws = await connectWs(server.url); |
| 165 | + sockets.push(ws); |
| 166 | + ws.send( |
| 167 | + JSON.stringify({ |
| 168 | + event: "start", |
| 169 | + start: { streamSid: route.streamSid, callSid: route.callSid }, |
| 170 | + }), |
| 171 | + ); |
| 172 | + } |
| 173 | + |
| 174 | + await vi.waitFor(() => { |
| 175 | + expect(salesProvider.createBridge).toHaveBeenCalledTimes(1); |
| 176 | + expect(supportProvider.createBridge).toHaveBeenCalledTimes(1); |
| 177 | + expect(salesConnect).toHaveBeenCalledTimes(1); |
| 178 | + expect(supportConnect).toHaveBeenCalledTimes(1); |
| 179 | + }); |
| 180 | + expect(salesProvider.createBridge).toHaveBeenCalledWith( |
| 181 | + expect.objectContaining({ |
| 182 | + agentId: "sales", |
| 183 | + providerConfig: { credentialOwner: "sales", model: "gpt-realtime" }, |
| 184 | + }), |
| 185 | + ); |
| 186 | + expect(supportProvider.createBridge).toHaveBeenCalledWith( |
| 187 | + expect.objectContaining({ |
| 188 | + agentId: "support", |
| 189 | + providerConfig: { credentialOwner: "support", model: "grok-voice" }, |
| 190 | + }), |
| 191 | + ); |
| 192 | + expect( |
| 193 | + mocks.resolveConfiguredRealtimeVoiceProvider.mock.calls.map( |
| 194 | + ([options]) => (options as { agentId?: string }).agentId, |
| 195 | + ), |
| 196 | + ).toEqual(["sales", "support"]); |
| 197 | + |
| 198 | + for (const ws of sockets) { |
| 199 | + const closed = waitForClose(ws); |
| 200 | + ws.close(1000); |
| 201 | + await closed; |
| 202 | + } |
| 203 | + await vi.waitFor(() => expect(runtime?.manager.getActiveCalls()).toHaveLength(0)); |
| 204 | + } finally { |
| 205 | + await runtime?.stop(); |
| 206 | + for (const ws of sockets) { |
| 207 | + if (ws.readyState !== WebSocket.CLOSED) { |
| 208 | + ws.terminate(); |
| 209 | + } |
| 210 | + } |
| 211 | + await Promise.all(servers.map((server) => server.close())); |
| 212 | + resetPluginStateStoreForTests(); |
| 213 | + } |
| 214 | + }); |
| 215 | +}); |
0 commit comments