From a4a725de91528887862f3e722bf91337b523fa42 Mon Sep 17 00:00:00 2001 From: Dotta Date: Tue, 27 Oct 2026 05:27:04 -0500 Subject: [PATCH] Complete interrupted inbound voice approvals on session reuse Co-Authored-By: Paperclip --- ...10-25-voice-inbound-cleanup-sleep-audit.md | 27 +++++++++++++ .../voice-session-store.integration.test.ts | 38 ++++++++++++++++++ .../src/services/voice/voice-session-store.ts | 39 ++++++++++++------- 3 files changed, 91 insertions(+), 13 deletions(-) diff --git a/doc/plans/2026-10-25-voice-inbound-cleanup-sleep-audit.md b/doc/plans/2026-10-25-voice-inbound-cleanup-sleep-audit.md index 97e9aefc7cc..50bd2c486e9 100644 --- a/doc/plans/2026-10-25-voice-inbound-cleanup-sleep-audit.md +++ b/doc/plans/2026-10-25-voice-inbound-cleanup-sleep-audit.md @@ -245,3 +245,30 @@ path through restoring the original account, but a permanently unavailable provider needs a deliberate ownership/product policy. A retry cap, elapsed time, or ambiguous 404 is not evidence that a billable call ended. Do not manufacture cleanup confirmation or silently discard the obligation to unblock deletion. + +## Retrying an interrupted approval (2026-10-27) + +Older versions could commit a private session or guest promotion before writing +the admission binding. Retrying approval then found the existing session and +returned before the new atomic binding helper ran. The inbound API rejected the +still-approving admission with “This call ended during approval.” + +Reservation now validates the inbound admission before the existing-session +return. It uses the existing session authorizer to check current liveness, +expiry, generation, credentials, caller and task access, then checks the exact +admission/session identity before binding in the same transaction. Lock order +remains endpoint, connection, admission, session. A matching provider session ID +alone cannot establish approval. Already approved idempotent calls remain valid +and do not rewrite the binding. Browser and outbound reservation behavior stays +with the existing path. This adds no table, timer or recovery wrapper. + +Both direct and promoted-guest retry regressions failed through the real inbound +API before the correction. They now return the same session without starting or +ending another provider call. Ended, expired and token-changed sessions are +rejected without binding. Existing atomic handoff and approval-authority cases +also pass. An initial negative expiry fixture violated the database timestamp +constraint; it was corrected to represent a valid session that has expired. +All 132 cases across the complete voice-session and inbound-cleanup suites pass +on separate fresh databases, and server typechecking passes. Downstream +integration and latest-head CI remain required. The separate company-deletion +cleanup findings are not resolved by this correction. diff --git a/server/src/__tests__/voice-session-store.integration.test.ts b/server/src/__tests__/voice-session-store.integration.test.ts index 0ff9c0ed413..870c38e5531 100644 --- a/server/src/__tests__/voice-session-store.integration.test.ts +++ b/server/src/__tests__/voice-session-store.integration.test.ts @@ -1414,6 +1414,44 @@ const support = external ? { supported: true } : await getEmbeddedPostgresTestSu await expect(approval).resolves.toMatchObject({ state: "approved", sessionId: session.id }); } finally { release(); await approval.catch(() => undefined); vi.useRealTimers(); } }); + it.each([false, true])("finishes an interrupted inbound approval using its existing live session (guest=%s)", async guest => { + const f = await inboundFixture(guest); + if (guest) await f.tool("submit_request", { text: "A public request before private approval" }); + const input = { approve: true, approvalCode: f.call.approvalCode, issueId: f.issueId }; + const approved = await f.service.inbound.decide(f.companyId, f.endpointId, f.call.id, f.input.caller, input); + // Older versions committed session creation/promotion before a separate + // admission binding. Reconstruct a crash in that gap, then retry the API. + await db.update(chatVoiceInboundCalls).set({ state: "approving", sessionId: guest ? approved.sessionId : null }) + .where(eq(chatVoiceInboundCalls.id, f.call.id)); + await expect(f.service.inbound.decide(f.companyId, f.endpointId, f.call.id, f.input.caller, input)) + .resolves.toMatchObject({ state: "approved", sessionId: approved.sessionId }); + await expect(f.service.start({ companyId: f.companyId, endpointId: f.endpointId, issueId: f.issueId, + caller: f.input.caller, idempotencyKey: `inbound:${f.call.id}`, maxDurationSeconds: 600, + mode: "inbound_phone", providerSessionId: f.event.session_id, toolToken: f.capability })) + .resolves.toMatchObject({ session: { id: approved.sessionId } }); + const sessions = await db.select().from(chatVoiceSessions).where(eq(chatVoiceSessions.providerSessionId, f.event.session_id)); + expect(sessions).toHaveLength(1); + expect(sessions[0]).toMatchObject({ id: approved.sessionId, callerId: f.callerId, issueId: f.issueId }); + expect(f.transport.createBrowserSession).not.toHaveBeenCalled(); + expect(f.transport.createPhoneSession).not.toHaveBeenCalled(); + expect(f.transport.endSession).not.toHaveBeenCalled(); + }); + + it.each(["ended", "expired", "token"] as const)("does not repair an interrupted approval after its session is %s", async change => { + const f = await inboundFixture(); + const input = { approve: true, approvalCode: f.call.approvalCode, issueId: f.issueId }; + const approved = await f.service.inbound.decide(f.companyId, f.endpointId, f.call.id, f.input.caller, input); + await db.update(chatVoiceInboundCalls).set({ state: "approving", sessionId: null }).where(eq(chatVoiceInboundCalls.id, f.call.id)); + await db.update(chatVoiceSessions).set(change === "ended" ? { state: "ended", endedAt: new Date() } + : change === "expired" ? { createdAt: new Date(Date.now() - 2000), expiresAt: new Date(Date.now() - 1000) } : { toolTokenHash: "a".repeat(64) }) + .where(eq(chatVoiceSessions.id, approved.sessionId!)); + await expect(f.service.inbound.decide(f.companyId, f.endpointId, f.call.id, f.input.caller, input)) + .rejects.toMatchObject({ status: 403 }); + const [call] = await db.select().from(chatVoiceInboundCalls).where(eq(chatVoiceInboundCalls.id, f.call.id)); + expect(call).toMatchObject({ state: "approving", sessionId: null }); + expect(await db.select().from(chatVoiceSessions).where(eq(chatVoiceSessions.providerSessionId, f.event.session_id))).toHaveLength(1); + }); + it("requires approval of the specific incoming call before delivering any private work", async () => { const f = await inboundFixture(); expect(await f.service.inbound.lifecycle(f.endpoint.publicId, f.signed.body, f.signed.headers)).toEqual(f.response); diff --git a/server/src/services/voice/voice-session-store.ts b/server/src/services/voice/voice-session-store.ts index bfd1ee9feda..ecbf9f965b8 100644 --- a/server/src/services/voice/voice-session-store.ts +++ b/server/src/services/voice/voice-session-store.ts @@ -167,29 +167,42 @@ export function voiceSessionStore(db: Db, options: { allowLocalBoard: boolean; n await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`voice:${input.companyId}:${input.caller.id}:${input.idempotencyKey}`}, 0))`); await authorizeCaller(tx, input.companyId, input.caller); const previous = await tx.select().from(chatVoiceSessions).where(and(eq(chatVoiceSessions.companyId, input.companyId), eq(chatVoiceSessions.callerId, input.caller.id), eq(chatVoiceSessions.idempotencyKey, input.idempotencyKey))).then((rows) => rows[0]); - if (previous) { - if (previous.requestFingerprint !== input.requestFingerprint || previous.endpointId !== input.endpointId) throw conflict("Voice request key was already used for different work"); - await authorizeConnection(tx, await endpointContext(tx, input.companyId, input.endpointId), input.caller); - await authorizeTask(tx, input.companyId, previous.issueId, input.caller); - return { session: previous, created: false as const }; - } + if (previous && (previous.requestFingerprint !== input.requestFingerprint || previous.endpointId !== input.endpointId)) throw conflict("Voice request key was already used for different work"); const context = await endpointContext(tx, input.companyId, input.endpointId); await authorizeConnection(tx, context, input.caller); - if (context.generation < 1 || input.maxDurationSeconds < 30 || input.maxDurationSeconds > 1800 || !Number.isInteger(input.maxDurationSeconds)) throw conflict("Voice setup or duration is invalid"); - let inboundAdmissionId: string | undefined; + let inboundAdmission: typeof chatVoiceInboundCalls.$inferSelect | undefined; async function bindInboundSession(sessionId: string) { - if (!inboundAdmissionId) return; + if (!inboundAdmission || inboundAdmission.state === "approved" && inboundAdmission.sessionId === sessionId) return; // Admission expiry must relinquish cleanup in the same commit that // establishes an authorized owner for the existing provider call. - await notifyVoiceInbound(tx, { kind: "admission", id: inboundAdmissionId }); + await notifyVoiceInbound(tx, { kind: "admission", id: inboundAdmission.id }); await tx.update(chatVoiceInboundCalls).set({ state: "approved", sessionId, updatedAt: new Date() }) - .where(eq(chatVoiceInboundCalls.id, inboundAdmissionId)); + .where(eq(chatVoiceInboundCalls.id, inboundAdmission.id)); } if (input.mode === "inbound_phone") { const [admission] = await tx.select().from(chatVoiceInboundCalls).where(and(eq(chatVoiceInboundCalls.companyId, input.companyId), eq(chatVoiceInboundCalls.endpointId, input.endpointId), eq(chatVoiceInboundCalls.providerSessionId, input.providerSessionId ?? ""))).for("update"); - if (!admission || admission.state !== "approving" || admission.approvedByUserId !== input.caller.id || admission.callerAuthority !== input.caller.authority || admission.expiresAt.getTime() <= Date.now() || admission.generation !== context.generation || admission.credentialFingerprint !== context.fingerprint || admission.toolTokenHash !== voiceTokenHash(input.toolToken ?? "") || input.idempotencyKey !== `inbound:${admission.id}`) throw forbidden("This live call has not been approved for private work"); - inboundAdmissionId = admission.id; + const approvedRetry = previous && admission?.state === "approved" && admission.sessionId === previous.id; + if (!admission || admission.state !== "approving" && !approvedRetry || admission.approvedByUserId !== input.caller.id || admission.callerAuthority !== input.caller.authority || admission.expiresAt.getTime() <= Date.now() || admission.generation !== context.generation || admission.credentialFingerprint !== context.fingerprint || admission.toolTokenHash !== voiceTokenHash(input.toolToken ?? "") || input.idempotencyKey !== `inbound:${admission.id}`) throw forbidden("This live call has not been approved for private work"); + inboundAdmission = admission; } + if (previous) { + if (inboundAdmission) { + // A legacy approval may have committed the session before binding the + // admission. Lock admission before session, as inbound cleanup does. + const { session } = await authorizeSession(tx, input.companyId, previous.id); + if (session.mode !== "inbound_phone" || session.providerSessionId !== input.providerSessionId + || session.callerId !== input.caller.id || session.callerAuthority !== input.caller.authority + || session.approvedByUserId !== input.caller.id || session.toolTokenHash !== inboundAdmission.toolTokenHash + || inboundAdmission.sessionId !== null && inboundAdmission.sessionId !== session.id + || inboundAdmission.requestedIssueId !== null && inboundAdmission.requestedIssueId !== session.issueId) + throw forbidden("This live call has not been approved for private work"); + await bindInboundSession(session.id); + return { session, created: false as const }; + } + await authorizeTask(tx, input.companyId, previous.issueId, input.caller); + return { session: previous, created: false as const }; + } + if (context.generation < 1 || input.maxDurationSeconds < 30 || input.maxDurationSeconds > 1800 || !Number.isInteger(input.maxDurationSeconds)) throw conflict("Voice setup or duration is invalid"); const binding = await input.prepareBinding(tx); const task = await authorizeTask(tx, input.companyId, binding.issueId, input.caller); const conversation = await tx.select().from(chatConversations).where(and(eq(chatConversations.id, binding.conversationId), eq(chatConversations.companyId, input.companyId), eq(chatConversations.endpointId, input.endpointId), eq(chatConversations.issueId, binding.issueId))).then((rows) => rows[0]);