diff --git a/server/src/__tests__/voice-session-store.integration.test.ts b/server/src/__tests__/voice-session-store.integration.test.ts index 2f75d13e446..527eb64a4fa 100644 --- a/server/src/__tests__/voice-session-store.integration.test.ts +++ b/server/src/__tests__/voice-session-store.integration.test.ts @@ -22,7 +22,7 @@ import { documentService } from "../services/documents.js"; import { applyConnectorSkills, prepareConnectorSkillDelivery, resolveConnectorAssignments } from "../services/connector-runtime.js"; import { VOICE_RESULT_NOTIFICATION } from "@paperclipai/shared"; import { createHash, createHmac, randomUUID } from "node:crypto"; -import { eq } from "drizzle-orm"; +import { and, eq, sql } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; import { applyPendingMigrations, chatActions, instanceUserRoles, principalPermissionGrants, environments, chatVoiceInboundCalls, chatVoicePhoneLines, chatVoiceReports, heartbeatRuns, toolCatalogEntries, toolProfileBindings, chatVoiceCallbacks, agentWakeupRequests, issueThreadInteractions, issueQuestionResponseDeliveries, issueComments, agents, chatConversations, chatDeliveries, chatEndpoints, chatPublications, chatVoiceReplies, chatVoiceSessions, chatVoiceToolCalls, companies, companyMemberships, companySecrets, connectionGrants, connectionGrantMembers, createDb, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, issues, toolApplications, toolConnections, toolConnectionInstalls } from "@paperclipai/db"; import { configureSpekoSessionTools } from "../services/voice/speko-tool-setup.js"; @@ -1845,6 +1845,38 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu expect(history).toHaveLength(1); expect(history[0]).toMatchObject({id: call.id, state: "ended"}); expect(JSON.stringify(history)).not.toContain("approvalCode"); expect(JSON.stringify(history)).not.toContain("toolToken"); }); + it("waits for a concurrent membership lock instead of failing board incoming-call requests", async () => { + // The board polls the incoming-call list every two seconds. + // A NOWAIT share lock failed that poll with 55P03 whenever another + // transaction held the caller's membership row. + const f = await inboundFixture(); + let release!: () => void, locked!: () => void; + const released = new Promise(resolve => { release = resolve; }); + const held = new Promise(resolve => { locked = resolve; }); + const holder = db.transaction(async tx => { + await tx.select({ id: companyMemberships.id }).from(companyMemberships).where(and(eq(companyMemberships.companyId, f.companyId), + eq(companyMemberships.principalId, f.callerId))).for("no key update"); + locked(); await released; + }); + await held; + const requests = Promise.allSettled([ + f.service.inbound.list(f.companyId, f.endpointId, f.input.caller), + f.service.inbound.decide(f.companyId, f.endpointId, f.call.id, f.input.caller, { approve: false, approvalCode: f.call.approvalCode }), + ]); + let settledUnderLock: unknown; + void requests.then(outcomes => { settledUnderLock = outcomes; }); + try { + await vi.waitFor(async () => { + expect(settledUnderLock).toBeUndefined(); + const [waiting] = await db.execute(sql`select count(*)::int as count from pg_stat_activity + where datname = current_database() and wait_event_type = 'Lock'`) as unknown as Array<{ count: number }>; + expect(waiting.count).toBe(2); + }, { timeout: 5000 }); + } finally { release(); await holder; } + const [list, decision] = await requests; + expect(list).toMatchObject({ status: "fulfilled" }); + expect(decision).toMatchObject({ status: "fulfilled", value: { id: f.call.id, state: "denied" } }); + }); it("uses task-comment follow-ups for guest clarifications and rejects protected question waits", async () => { const f = await inboundFixture(true); await f.tool("submit_request", {text: "Draft a public inquiry"}); diff --git a/server/src/services/voice/voice-inbound-service.ts b/server/src/services/voice/voice-inbound-service.ts index b270e420caf..4c958fdb84f 100644 --- a/server/src/services/voice/voice-inbound-service.ts +++ b/server/src/services/voice/voice-inbound-service.ts @@ -34,7 +34,11 @@ export function voiceInboundService(db: Db, options: { voicePrompt: string; lowTrustVoicePrompt: string; }) { - const store = voiceSessionStore(db, {...options, nonblockingAuthority: true}), provider = options.provider ?? createSpekoProvider; + // Provider callbacks answer a live call, so their authority checks fail fast + // instead of queueing behind a concurrent change. Board requests (including + // the two-second incoming-call poll) wait like other board routes; NOWAIT + // there turned ordinary membership-row contention into a 500. + const store = voiceSessionStore(db, {...options, nonblockingAuthority: true}), boardStore = voiceSessionStore(db, options), provider = options.provider ?? createSpekoProvider; const issueSvc = issueService(db), environments = environmentService(db); async function sandboxChoices(companyId: string) { const choices = await environments.list({driver: "sandbox", status: "active"}); @@ -51,7 +55,7 @@ export function voiceInboundService(db: Db, options: { async function enabled() { if (!(await instanceSettingsService(db).getExperimental()).enableChatConnectors) throw forbidden("Voice connections are disabled"); } async function manager(companyId: string, caller: VoiceCaller, transaction?: VoiceTransaction) { const check = async (tx: VoiceTransaction) => { - await store.authorizeCaller(tx, companyId, caller); + await boardStore.authorizeCaller(tx, companyId, caller); if (caller.authority === "local_board" || caller.authority === "instance_admin" || (await authorizationService(tx).decidePrincipalGrant({companyId, principalType: "user", principalId: caller.id, permissionKey: "tools:manage_connections", action: "tools:manage_connections"})).allowed) return; throw forbidden("Missing permission: tools:manage_connections"); }; @@ -71,7 +75,7 @@ export function voiceInboundService(db: Db, options: { await assertEnvironmentSelectionForCompany(environments, companyId, input.lowTrustEnvironmentId, {allowedDrivers: ["sandbox"]}); if (!(await sandboxChoices(companyId)).some(e => e.id === input.lowTrustEnvironmentId)) throw forbidden("Choose a sandbox available to this company"); } - const context = await db.transaction(tx => store.endpointContext(tx, companyId, endpointId)); + const context = await db.transaction(tx => boardStore.endpointContext(tx, companyId, endpointId)); const credentials = await options.credentials(row, context.fingerprint), client = provider(credentials.apiKey); let numbers = await client.listPhoneNumbers(), number = numbers.find(n => n.id === input.numberId && n.organizationId === row.providerAccountId); if (!number || number.agentId && number.agentId !== credentials.agentId || number.routeToBrokerId || number.suspendedAt || number.direction === "outbound") throw conflict("Choose an available incoming number in this Speko workspace"); @@ -84,7 +88,7 @@ export function voiceInboundService(db: Db, options: { if (!number) throw conflict("Speko could not confirm this phone number"); await db.transaction(async tx => { await manager(companyId, caller, tx); - const current = await store.endpointContext(tx, companyId, endpointId); + const current = await boardStore.endpointContext(tx, companyId, endpointId); if (current.fingerprint !== context.fingerprint || current.generation !== context.generation) throw conflict("Voice configuration changed. Refresh before saving."); await tx.insert(chatVoicePhoneLines).values({companyId, endpointId, providerNumberId: number!.id, phoneNumber: number!.e164, enabled: input.enabled, guestIntake: input.guestIntake ?? false, lowTrustEnvironmentId: input.lowTrustEnvironmentId ?? null}).onConflictDoUpdate({target: chatVoicePhoneLines.endpointId, set: {providerNumberId: number!.id, phoneNumber: number!.e164, enabled: input.enabled, guestIntake: input.guestIntake ?? false, ...(input.lowTrustEnvironmentId !== undefined ? {lowTrustEnvironmentId: input.lowTrustEnvironmentId} : {}), updatedAt: new Date()}}); await tx.insert(activityLog).values({companyId, actorType: "user", actorId: caller.id, action: "voice.phone_line.configured", entityType: "chat_endpoint", entityId: endpointId, details: {enabled: input.enabled, guestIntake: input.guestIntake ?? false}}); @@ -212,16 +216,16 @@ export function voiceInboundService(db: Db, options: { } async function list(companyId: string, endpointId: string, caller: VoiceCaller) { await enabled(); - await db.transaction(async tx => { await store.authorizeCaller(tx, companyId, caller); const context = await store.endpointContext(tx, companyId, endpointId); await store.authorizeConnection(tx, context, caller); }); + await db.transaction(async tx => { await boardStore.authorizeCaller(tx, companyId, caller); const context = await boardStore.endpointContext(tx, companyId, endpointId); await boardStore.authorizeConnection(tx, context, caller); }); const rows = await db.select().from(chatVoiceInboundCalls).where(and(eq(chatVoiceInboundCalls.companyId, companyId), eq(chatVoiceInboundCalls.endpointId, endpointId), inArray(chatVoiceInboundCalls.state, ["guest_intake", "awaiting_approval", "approving"]))).orderBy(desc(chatVoiceInboundCalls.createdAt)).limit(20); return rows.filter(row => !row.approvedByUserId || row.approvedByUserId === caller.id).map(projection); } async function history(companyId: string, endpointId: string, caller: VoiceCaller) { await enabled(); return db.transaction(async tx => { - await store.authorizeCaller(tx, companyId, caller); - const context = await store.endpointContext(tx, companyId, endpointId); - await store.authorizeConnection(tx, context, caller); + await boardStore.authorizeCaller(tx, companyId, caller); + const context = await boardStore.endpointContext(tx, companyId, endpointId); + await boardStore.authorizeConnection(tx, context, caller); const rows = await tx.select({id: chatVoiceInboundCalls.id, state: chatVoiceInboundCalls.state, createdAt: chatVoiceInboundCalls.createdAt, updatedAt: chatVoiceInboundCalls.updatedAt}).from(chatVoiceInboundCalls).where(and(eq(chatVoiceInboundCalls.companyId, companyId), eq(chatVoiceInboundCalls.endpointId, endpointId), isNull(chatVoiceInboundCalls.sessionId), inArray(chatVoiceInboundCalls.state, ["denied", "expired", "ended"]))).orderBy(desc(chatVoiceInboundCalls.createdAt)).limit(20); return rows.map(row => ({...row, state: row.state as "denied" | "expired" | "ended", createdAt: row.createdAt.toISOString(), updatedAt: row.updatedAt.toISOString()})); }); @@ -229,8 +233,8 @@ export function voiceInboundService(db: Db, options: { async function decide(companyId: string, endpointId: string, callId: string, caller: VoiceCaller, input: {approve: boolean; approvalCode: string; issueId?: string}) { await enabled(); let admission = await db.transaction(async tx => { - await store.authorizeCaller(tx, companyId, caller); - const context = await store.endpointContext(tx, companyId, endpointId); await store.authorizeConnection(tx, context, caller); + await boardStore.authorizeCaller(tx, companyId, caller); + const context = await boardStore.endpointContext(tx, companyId, endpointId); await boardStore.authorizeConnection(tx, context, caller); const [row] = await tx.select().from(chatVoiceInboundCalls).where(and(eq(chatVoiceInboundCalls.id, callId), eq(chatVoiceInboundCalls.companyId, companyId), eq(chatVoiceInboundCalls.endpointId, endpointId))).for("update"); if (!row) throw notFound("Incoming call not found"); if (row.approvalCode !== input.approvalCode) throw forbidden("Confirm the approval code spoken on this live call"); @@ -239,7 +243,7 @@ export function voiceInboundService(db: Db, options: { if (row.state === "approved") { if (row.requestedIssueId !== (input.issueId ?? row.intakeIssueId ?? null)) throw conflict("This call is already bound to another task"); return row; } if (!["guest_intake", "awaiting_approval", "approving"].includes(row.state)) throw conflict("This incoming call is no longer waiting for approval"); if (row.state === "approving" && (!input.approve || row.requestedIssueId !== (input.issueId ?? row.intakeIssueId ?? null))) throw conflict("This call is already being approved"); - if (input.issueId) await store.authorizeTask(tx, companyId, input.issueId, caller); + if (input.issueId) await boardStore.authorizeTask(tx, companyId, input.issueId, caller); await notifyVoiceInbound(tx, { kind: "admission", id: row.id }); const [changed] = await tx.update(chatVoiceInboundCalls).set({state: input.approve ? "approving" : row.state === "guest_intake" ? "ended" : "denied", approvedByUserId: caller.id, callerAuthority: caller.authority, requestedIssueId: input.issueId ?? row.intakeIssueId ?? null, updatedAt: new Date()}).where(eq(chatVoiceInboundCalls.id, row.id)).returning(); await tx.insert(activityLog).values({companyId, actorType: "user", actorId: caller.id, action: input.approve ? "voice.inbound.approval_started" : row.state === "guest_intake" ? "voice.low_trust_call.ended" : "voice.inbound.denied", entityType: "voice_inbound_call", entityId: row.id});