From 24751a27c15799dd528757c751cbab2ea38a580c Mon Sep 17 00:00:00 2001 From: Dotta Date: Fri, 9 Oct 2026 19:38:01 -0500 Subject: [PATCH] fix(voice): preserve pending work across call and settings changes Co-Authored-By: Paperclip --- .../voice-session-store.integration.test.ts | 37 +++++++++++++ .../external-chat-question-response.ts | 54 ++++++++++++++++++- .../external-chat-wait.integration.test.ts | 16 ++++-- .../src/services/voice/voice-session-store.ts | 23 +++++++- 4 files changed, 122 insertions(+), 8 deletions(-) diff --git a/server/src/__tests__/voice-session-store.integration.test.ts b/server/src/__tests__/voice-session-store.integration.test.ts index e547082a20c..d83264f5b68 100644 --- a/server/src/__tests__/voice-session-store.integration.test.ts +++ b/server/src/__tests__/voice-session-store.integration.test.ts @@ -460,6 +460,25 @@ const support = await getEmbeddedPostgresTestSupport(); expect((await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, f.id)))[0]).toMatchObject({ status: "answered", resolvedByUserId: f.callerId }); expect(await db.select().from(chatDeliveries).where(eq(chatDeliveries.endpointId, f.endpointId))).toHaveLength(0); }); + it("presents an unanswered question again after reconnect so the caller can answer it", async () => { + const f = await questionFixture(); + await f.store.runTool(f.toolInput("get_updates", {cursor: 0})); + await db.update(chatVoiceSessions).set({state: "ended", endedAt: new Date()}).where(eq(chatVoiceSessions.id, f.sessionId)); + const resumed = await f.store.reserve({...f.request, idempotencyKey: randomUUID()}); + if (!resumed.created) throw new Error("Expected resumed call"); + const providerSessionId = randomUUID(); + await db.update(chatVoiceSessions).set({state: "active", providerSessionId}).where(eq(chatVoiceSessions.id, resumed.session.id)); + const tool = (name: SpekoToolEnvelope["tool"], args: SpekoToolEnvelope["args"]) => { + const toolId = randomUUID(); + const envelope = {session_id: providerSessionId, tool_call_id: toolId, idempotency_key: `${providerSessionId}:${toolId}`, tool: name, args} as SpekoToolEnvelope; + return f.store.runTool({...f.toolInput(name, args), sessionId: resumed.session.id, token: resumed.token, + envelope, webhookId: toolId, fingerprint: createHash("sha256").update(JSON.stringify(envelope)).digest("hex")}); + }; + expect(await f.store.notification(f.companyId, resumed.session.id, f.callerId)).not.toBeNull(); + expect(await tool("get_updates", {cursor: 0})).toMatchObject({updates: [{question: {interactionId: f.id}}]}); + expect(await tool("answer_question", {interactionId: f.id, answers: [{questionId: "color", optionIds: ["cobalt"]}]})).toMatchObject({status: "answered"}); + expect(await db.select().from(issueQuestionResponseDeliveries).where(eq(issueQuestionResponseDeliveries.interactionId, f.id))).toHaveLength(1); + }); it("refuses voice answers when the exact question recipient changes", async () => { const f = await questionFixture(); await f.store.runTool(f.toolInput("get_updates", { cursor: 0 })); @@ -742,6 +761,24 @@ const support = await getEmbeddedPostgresTestSupport(); await db.update(issues).set({executionWorkspaceSettings: {mode: "isolated_workspace", environmentId: randomUUID()}}).where(eq(issues.id, task.id)); await expect(f.tool("get_updates", {cursor: 0})).rejects.toMatchObject({status: 403}); }); + it("keeps accepted guest work in its saved sandbox when line settings change, but rejects an archived sandbox", async () => { + const first = randomUUID(), next = randomUUID(); + await db.insert(environments).values([{id: first, name: first, driver: "sandbox", config: {provider: "daytona"}}, + {id: next, name: next, driver: "sandbox", config: {provider: "daytona"}}]); + const f = await inboundFixture(true, first); + await f.tool("submit_request", {text: "Inspect disk space"}); + await db.update(chatVoicePhoneLines).set({lowTrustEnvironmentId: next}).where(eq(chatVoicePhoneLines.endpointId, f.endpointId)); + expect(await f.tool("submit_request", {text: "Also check free space"})).toMatchObject({status: "accepted"}); + const [task] = await db.select().from(issues).where(eq(issues.id, f.call.intakeIssueId!)); + expect(task.executionWorkspaceSettings?.environmentId).toBe(first); + const [session] = await db.select().from(chatVoiceSessions).where(eq(chatVoiceSessions.id, f.call.sessionId!)); + await db.update(chatVoiceSessions).set({state: "ended", endedAt: new Date()}).where(eq(chatVoiceSessions.id, session.id)); + await db.update(chatVoiceInboundCalls).set({state: "ended"}).where(eq(chatVoiceInboundCalls.id, f.call.id)); + const principal = `voice:${session.id}`; + expect(await db.transaction(tx => voiceSessionStore(db, {allowLocalBoard: false}).authorizePrincipal(tx, f.companyId, f.endpointId, principal))).toMatchObject({allowed: true}); + await db.update(environments).set({status: "archived"}).where(eq(environments.id, first)); + await expect(db.transaction(tx => voiceSessionStore(db, {allowLocalBoard: false}).authorizePrincipal(tx, f.companyId, f.endpointId, principal))).rejects.toMatchObject({status: 403}); + }); it("confines explicitly enabled public calls to one new low-trust conversation task", async () => { const f = await inboundFixture(true), toolId = randomUUID(); expect(f.response).not.toHaveProperty("approvalCode"); diff --git a/server/src/services/native-runtime/external-chat-question-response.ts b/server/src/services/native-runtime/external-chat-question-response.ts index e46faa19b91..df45788684a 100644 --- a/server/src/services/native-runtime/external-chat-question-response.ts +++ b/server/src/services/native-runtime/external-chat-question-response.ts @@ -7,6 +7,7 @@ import { chatConversations, chatDeliveries, chatEndpoints, + chatExternalPrincipals, chatIdentityLinks, chatVoiceSessions, chatVoiceToolCalls, @@ -25,7 +26,7 @@ import { validateChatQuestionFormSubmission, } from "../chat-question-forms.js"; import { questionResponseDeliveryValues } from "../question-response-delivery.js"; -import { currentVoiceCredentialFingerprint } from "../voice/voice-session-store.js"; +import { voiceSessionStore, type VoiceTransaction, currentVoiceCredentialFingerprint } from "../voice/voice-session-store.js"; import { nativeSha256 } from "./canonical.js"; export const EXTERNAL_CHAT_QUESTION_RESPONSE_KEY = @@ -443,6 +444,57 @@ async function resolveQuestionResponseChain( // Terminal acknowledgment publications use the same interaction ID. // Only a question actually delivered before its answer can be proof. lte(chatVoiceReplies.deliveredAt, interaction.resolvedAt))); + if (proofs.length === 0 && interaction.resolvedByRunId === null) { + // The authenticated task-page answer commits the canonical interaction + // and response delivery too. Bind it to the original voice requester; + // do not require hearing the question or fabricate a signed-tool receipt. + const origins = await tx.select({ session: chatVoiceSessions, endpoint: chatEndpoints, + connection: toolConnections, conversation: chatConversations, comment: issueComments, + inbound: chatDeliveries, link: chatMessageLinks }).from(chatMessageLinks) + .innerJoin(issueComments, and(eq(issueComments.id, chatMessageLinks.commentId), eq(issueComments.companyId, binding.companyId), eq(issueComments.issueId, binding.issueId))) + .innerJoin(chatDeliveries, and(eq(chatDeliveries.id, chatMessageLinks.deliveryId), eq(chatDeliveries.companyId, binding.companyId), eq(chatDeliveries.endpointId, chatMessageLinks.endpointId), eq(chatDeliveries.conversationId, chatMessageLinks.conversationId))) + .innerJoin(chatExternalPrincipals, and(eq(chatExternalPrincipals.id, chatDeliveries.principalId), eq(chatExternalPrincipals.companyId, binding.companyId), eq(chatExternalPrincipals.provider, "speko"))) + .innerJoin(chatVoiceSessions, and(sql`${chatExternalPrincipals.externalId} = 'voice:' || ${chatVoiceSessions.id}::text`, eq(chatVoiceSessions.companyId, binding.companyId), eq(chatVoiceSessions.endpointId, chatMessageLinks.endpointId), eq(chatVoiceSessions.conversationId, chatMessageLinks.conversationId), eq(chatVoiceSessions.issueId, binding.issueId))) + .innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatVoiceSessions.endpointId), eq(chatEndpoints.companyId, binding.companyId))) + .innerJoin(toolConnections, and(eq(toolConnections.id, chatEndpoints.connectionId), eq(toolConnections.companyId, binding.companyId))) + .innerJoin(chatConversations, and(eq(chatConversations.id, chatVoiceSessions.conversationId), eq(chatConversations.companyId, binding.companyId), eq(chatConversations.endpointId, chatEndpoints.id))) + .where(and(eq(chatMessageLinks.companyId, binding.companyId), eq(chatMessageLinks.commentId, context.sourceCommentId), eq(chatMessageLinks.direction, "inbound"))); + if (origins.length !== 1) return null; + const { session, endpoint, connection, conversation, comment, inbound, link } = origins[0]!; + if (comment.deletedAt || inbound.state !== "processed" || comment.authorUserId !== interaction.resolvedByUserId + || session.callerId !== interaction.resolvedByUserId || !["member", "instance_admin", "local_board"].includes(session.callerAuthority) + || session.assignedAgentId !== binding.agentId || endpoint.assignedAgentId !== binding.agentId + || endpoint.provider !== "speko" || !["active", "verifying"].includes(endpoint.status) + || !connection.enabled || connection.status !== "active" || connection.transport !== "voice" + || session.generation !== record(endpoint.setup).runtimeGeneration + || session.credentialFingerprint !== await currentVoiceCredentialFingerprint(tx, binding.companyId, connection.credentialSecretRefs) + || !["active", "waiting"].includes(conversation.state) || conversation.issueId !== binding.issueId + || (parent && (parent.marker.endpointId !== endpoint.id || parent.marker.conversationId !== conversation.id))) return null; + try { + const store = voiceSessionStore(tx, { allowLocalBoard: session.callerAuthority === "local_board" }); + await store.authorizePrincipal(tx as unknown as VoiceTransaction, binding.companyId, endpoint.id, `voice:${session.id}`); + } catch (error) { + if (error && typeof error === "object" && "code" in error && error.code === "55P03") throw error; + return null; + } + const marker: Marker = { + schema: "paperclip.external_chat_question_response.v1", interactionId: interaction.id, + responseDeliveryId: delivery.id, sourceRunId: source.id, sourceCommentId: context.sourceCommentId, + endpointId: endpoint.id, conversationId: conversation.id, + bindingSha256: nativeSha256({ binding: {companyId: binding.companyId, issueId: binding.issueId, runId: binding.runId, agentId: binding.agentId}, responseDeliveryId: delivery.id, payloadSha256: delivery.payloadSha256, + sourceRunId: source.id, sourceCommentId: context.sourceCommentId, sourceOrigin: sourceContext.source, + ...(parent ? { sourceQuestionResponseSha256: parent.marker.bindingSha256 } : {}), + interaction: { id: interaction.id, payload: interaction.payload, result: interaction.result, + resolvedAt: interaction.resolvedAt.toISOString(), resolvedByUserId: interaction.resolvedByUserId }, + boardResponse: { sessionId: session.id, callerId: session.callerId, generation: session.generation, + credentialFingerprint: session.credentialFingerprint, inboundId: inbound.id, linkId: link.id }, + conversationGeneration: conversation.sessionGeneration, wakeId: wake.id }), + }; + if (!mint && nativeSha256(record(context[EXTERNAL_CHAT_QUESTION_RESPONSE_KEY])) !== nativeSha256(marker)) return null; + return { marker, provider, answeredAtMs: interaction.resolvedAt.getTime(), + interactionIds: [...(parent?.interactionIds ?? []), interaction.id], + authorizationContext: { ...context, source: "chat:speko", paperclipHarnessCheckedOut: false, paperclipExternalChatExecutionBound: true } }; + } if (proofs.length !== 1) return null; const proof = proofs[0]!; const { receipt, session, reply, publication, endpoint, connection, conversation } = proof; diff --git a/server/src/services/native-runtime/external-chat-wait.integration.test.ts b/server/src/services/native-runtime/external-chat-wait.integration.test.ts index 63c64f329e9..35ec5bb3edc 100644 --- a/server/src/services/native-runtime/external-chat-wait.integration.test.ts +++ b/server/src/services/native-runtime/external-chat-wait.integration.test.ts @@ -1118,7 +1118,7 @@ describe("native external-chat response wait", () => { }, ); - it.each(["native", "legacy"] as const)("requires the exact durable Speko answer receipt before authorizing a %s question continuation", async (sourceRuntime) => { + it.each((["native", "legacy"] as const).flatMap(sourceRuntime => (["voice", "board"] as const).map(answerRoute => ({sourceRuntime, answerRoute}))))("authorizes $sourceRuntime Speko question continuation from its exact $answerRoute answer", async ({sourceRuntime, answerRoute}) => { const f = await seedAnsweredChatTurn(); const [endpoint] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, f.endpointId)); const [connection] = await db.update(toolConnections).set({ transport: "voice", status: "active", enabled: true }).where(eq(toolConnections.id, endpoint.connectionId)).returning(); @@ -1136,9 +1136,14 @@ describe("native external-chat response wait", () => { toolTokenHash: "a".repeat(64), idempotencyKey: randomUUID(), requestFingerprint: "fixture", expiresAt: new Date(Date.now() + 60000) }); await db.insert(chatVoiceReplies).values({ companyId: f.companyId, sessionId, publicationId: f.publicationId, cursor: 1, deliveredAt: new Date(interaction.resolvedAt!.getTime() - 1) }); - const [receipt] = await db.insert(chatVoiceToolCalls).values({ companyId: f.companyId, sessionId, providerToolCallId: randomUUID(), + const [receipt] = answerRoute === "voice" ? await db.insert(chatVoiceToolCalls).values({ companyId: f.companyId, sessionId, providerToolCallId: randomUUID(), webhookId: randomUUID(), fingerprint: "signed-tool-fingerprint", tool: "answer_question", - response: { status: "answered", interactionId: f.interactionId, resultSha256: nativeSha256(interaction.result) } }).returning(); + response: { status: "answered", interactionId: f.interactionId, resultSha256: nativeSha256(interaction.result) } }).returning() : []; + if (answerRoute === "board") { + await db.update(chatExternalPrincipals).set({ provider: "speko", externalId: `voice:${sessionId}` }).where(eq(chatExternalPrincipals.id, f.principalId)); + await db.insert(chatVoiceToolCalls).values({companyId: f.companyId, sessionId, providerToolCallId: randomUUID(), + webhookId: randomUUID(), fingerprint: "accepted-source-request", tool: "submit_request", response: {status: "accepted"}}); + } // The answer also publishes a terminal acknowledgment. It cannot compete // with the pre-answer presentation as authority for the continuation. const [terminal] = await db.insert(chatPublications).values({ companyId: f.companyId, endpointId: f.endpointId, @@ -1153,9 +1158,10 @@ describe("native external-chat response wait", () => { await attestAnswer(f); expect(await authorizeChatConversationForBoundRun(db, f, f.context, "read")).toMatchObject({ conversationId: f.conversationId }); await db.update(companyMemberships).set({ status: "removed" }).where(eq(companyMemberships.principalId, f.userId)); - await expect(authorizeChatConversationForBoundRun(db, f, f.context, "read")).rejects.toThrow("paperclip_runner_chat_attachment_principal_denied"); + await expect(authorizeChatConversationForBoundRun(db, f, f.context, "read")).rejects.toThrow(answerRoute === "board" ? "paperclip_runner_chat_attachment_binding_denied" : "paperclip_runner_chat_attachment_principal_denied"); await db.update(companyMemberships).set({ status: "active" }).where(eq(companyMemberships.principalId, f.userId)); - await db.update(chatVoiceToolCalls).set({ response: { ...receipt.response, resultSha256: "different-answer" } }).where(eq(chatVoiceToolCalls.id, receipt.id)); + if (receipt) await db.update(chatVoiceToolCalls).set({ response: { ...receipt.response, resultSha256: "different-answer" } }).where(eq(chatVoiceToolCalls.id, receipt.id)); + else await db.update(issueComments).set({authorUserId: randomUUID()}).where(eq(issueComments.id, f.commentId)); expect(await resolve()).toBeNull(); }); it.each(["valid", "wrong_task", "revoked_identity", "wrong_answer_actor"] as const)( diff --git a/server/src/services/voice/voice-session-store.ts b/server/src/services/voice/voice-session-store.ts index 315c0f43a27..21a864c3730 100644 --- a/server/src/services/voice/voice-session-store.ts +++ b/server/src/services/voice/voice-session-store.ts @@ -1,3 +1,4 @@ +import { environmentService } from "../environments.js"; import { logger } from "../../middleware/logger.js"; import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; import { and, asc, desc, eq, gte, inArray, isNull, or, sql, type SQL } from "drizzle-orm"; @@ -106,9 +107,23 @@ export function voiceSessionStore(db: Db, options: { allowLocalBoard: boolean; n const policy = task?.executionPolicy?.authorizationPolicy as {trustPreset?: string; trustBoundary?: {mode?: string; companyId?: string; rootIssueId?: string; issueIds?: string[]; allowedAgentIds?: string[]; allowedToolClasses?: string[]; allowedSecretBindingIds?: string[]}} | undefined; const boundary = policy?.trustBoundary; if (!call || !line || !endpoint.allowDirectMessages || session.mode !== "inbound_phone" || session.callerId !== `guest:${call.id}` || call.providerSessionId !== session.providerSessionId || call.generation !== context.generation || call.credentialFingerprint !== context.fingerprint || call.toolTokenHash !== session.toolTokenHash || !["guest_intake", "ended"].includes(call.state) - || !task || (line.lowTrustEnvironmentId ?? null) !== (task.executionWorkspaceSettings?.environmentId ?? null) || task.hiddenAt || task.status === "cancelled" || task.originKind !== "chat_channel" || task.originId !== endpoint.id || task.assigneeAgentId !== session.assignedAgentId || session.assignedAgentId !== endpoint.assignedAgentId + || !task || task.hiddenAt || task.status === "cancelled" || task.originKind !== "chat_channel" || task.originId !== endpoint.id || task.assigneeAgentId !== session.assignedAgentId || session.assignedAgentId !== endpoint.assignedAgentId || task.sourceTrust?.preset !== LOW_TRUST_REVIEW_PRESET || task.sourceTrust.disposition !== "quarantined" || policy?.trustPreset !== LOW_TRUST_REVIEW_PRESET || boundary?.mode !== LOW_TRUST_REVIEW_PRESET || boundary.companyId !== endpoint.companyId || boundary.rootIssueId !== task.id || boundary.issueIds?.length !== 1 || boundary.issueIds[0] !== task.id || boundary.allowedAgentIds?.length !== 1 || boundary.allowedAgentIds[0] !== session.assignedAgentId || boundary.allowedToolClasses?.length !== 0 || boundary.allowedSecretBindingIds?.length !== 0) throw forbidden("The low-trust phone task boundary is no longer available"); + // The line selects environments for future calls. Accepted work keeps its + // task's saved sandbox, subject to current availability and company scope. + const savedSettings = task.executionWorkspaceSettings; + const savedEnvironmentId = typeof savedSettings?.environmentId === "string" ? savedSettings.environmentId : null; + const strategy = savedSettings?.workspaceStrategy as {type?: string} | undefined; + if (task.executionWorkspaceSettings?.mode !== "isolated_workspace" + || strategy?.type !== "cloud_sandbox") throw forbidden("The phone task sandbox boundary changed"); + if (savedEnvironmentId) { + const environments = environmentService(tx as unknown as Db); + const environment = await environments.getById(savedEnvironmentId); + const owners = await environments.listBoundCompanyIds(savedEnvironmentId); + if (!environment || environment.status !== "active" || environment.driver !== "sandbox" + || environment.config?.provider === "fake" || owners.length && !owners.includes(endpoint.companyId)) throw forbidden("The saved phone task sandbox is unavailable"); + } // Honor managed credential/install revocation without impersonating a user. const grants = await tx.select().from(connectionGrants).where(and(eq(connectionGrants.companyId, endpoint.companyId), eq(connectionGrants.connectionId, context.connection.id))); if (grants.length && !grants.some(g => g.status === "active" && g.kind === "organization" && voiceCredentialFingerprint(g.credentialSecretRefs) === voiceCredentialFingerprint(context.connection.credentialSecretRefs))) throw forbidden("The company phone credential grant is unavailable"); @@ -212,7 +227,11 @@ export function voiceSessionStore(db: Db, options: { allowLocalBoard: boolean; n return delivery.id; } function priorCallDeliveryBarrier(session: VoiceSessionRow, publicationId: string | SQL) { - return sql`exists (select 1 from chat_voice_replies r join chat_voice_sessions s + return sql`not exists (select 1 from chat_publications p join issue_thread_interactions i + on i.id::text = p.payload->>'interactionId' and i.company_id = p.company_id and i.issue_id = p.issue_id + where p.id = ${publicationId} and p.company_id = ${session.companyId} + and i.kind = 'ask_user_questions' and i.status = 'pending') + and exists (select 1 from chat_voice_replies r join chat_voice_sessions s on s.id = r.session_id and s.company_id = r.company_id where r.company_id = ${session.companyId} and r.publication_id = ${publicationId} and s.id <> ${session.id} and s.caller_id = ${session.callerId}