diff --git a/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md b/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md index cc7df120edd..0646390908a 100644 --- a/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md +++ b/doc/plans/2026-10-08-instance-sleep-and-scheduler-inventory.md @@ -423,11 +423,19 @@ Longer polling intervals alone do not complete an item. [app.ts](../../server/src/app.ts), [chat-channels.ts](../../server/src/services/chat-channels.ts). -- [ ] **JOB-02 — Email reconciliation.** Current: every **1s**, querying active - endpoints even when none exist. Change: initialize resource/pending state and - update on endpoint changes, webhook receipt, sends, and retries. **Complete - when:** empty mail state produces no polling SQL and new work activates the - worker without restart. Source: +- [x] **JOB-02 — Email reconciliation.** Replaced the unconditional **1s** + scan with startup recovery and transaction-aware wakes for endpoint activation, + pause/resume/removal, admitted events, and queued sends. Separate service + objects sharing the database owner wake the app worker after commit. The + worker restores its next deadline from persisted inbound/outbound retries and + catch-up state. No active inboxes means no recurring email SQL or timer. + Configured inboxes retain one-minute catch-up and live socket lease renewal + (NET-01/NET-02); this does not yet make an active inbox sleep indefinitely. + Intent reconciliation survives ambiguous transaction outcomes. Warm standby + suppresses SQL, and idle drain defers dispatch without losing its wake. + No new tables or provider infrastructure. Independent database roots and + direct SQL do not emit these process-local hints; startup and configured-inbox + catch-up remain the recovery boundaries. Source: [email-channels.ts](../../server/src/services/email-channels.ts). - [ ] **JOB-03 — Browser-use cleanup.** Current: every **3s** with due-session diff --git a/server/src/__tests__/cloud-warm-standby.test.ts b/server/src/__tests__/cloud-warm-standby.test.ts index 76247a35f3c..60cdc331114 100644 --- a/server/src/__tests__/cloud-warm-standby.test.ts +++ b/server/src/__tests__/cloud-warm-standby.test.ts @@ -3,6 +3,7 @@ import express from "express"; import request from "supertest"; import { afterEach, describe, expect, it, vi } from "vitest"; import type { Db } from "@paperclipai/db"; +import { installDatabaseWorkSignals } from "../../../packages/db/src/work-signals.js"; import { cloudWarmStandbyMiddleware, cloudWarmStandbyServerOptions } from "../middleware/cloud-warm-standby.js"; import { healthRoutes } from "../routes/health.js"; import { emailChannelService } from "../services/email-channels.js"; @@ -124,7 +125,7 @@ describe("unclaimed Cloud background work", () => { vi.useFakeTimers(); let enabled = false; const select = vi.fn(() => { throw new Error("SQL probe"); }); - const db = { select } as unknown as Db; + const db = installDatabaseWorkSignals({ select, execute: vi.fn(), transaction: vi.fn() }) as unknown as Db; const email = emailChannelService(db, { heartbeat: { wakeup: vi.fn() }, isBackgroundWorkEnabled: () => enabled }); const scheduler = createPluginJobScheduler({ db, diff --git a/server/src/__tests__/delivery-work-coordinator.test.ts b/server/src/__tests__/delivery-work-coordinator.test.ts index 1be5395f9df..c964714698c 100644 --- a/server/src/__tests__/delivery-work-coordinator.test.ts +++ b/server/src/__tests__/delivery-work-coordinator.test.ts @@ -27,7 +27,7 @@ function setup() { function task() { return { retryMs: 5000, run: vi.fn(async () => {}), hasPending: vi.fn(async () => false) }; } describe("delivery work coordinator", () => { - it("leaves five empty queues with no deadlines, timers, or periodic queries", async () => { + it("leaves empty queues with no deadlines, timers, or periodic queries", async () => { const s = setup(); const tasks = Object.values(DELIVERY_QUEUES).map(queue => { const t = task(); return { queue, t, worker: s.coordinator.register(queue, t) }; @@ -45,6 +45,21 @@ describe("delivery work coordinator", () => { expect(vi.getTimerCount()).toBe(0); expect(idleWorkSnapshot().active).toBe(0); }); + it("schedules maintenance without holding idle intent, and lets new work preempt it", async () => { + const s = setup(), t = task(); + let next: number | null = Date.now() + 60_000; + await s.coordinator.register(DELIVERY_QUEUES.email, { ...t, nextRunAt: () => next }).ready; + await vi.advanceTimersByTimeAsync(59_000); + expect(t.run).toHaveBeenCalledTimes(1); + await s.enqueue(DELIVERY_QUEUES.email); + await vi.advanceTimersByTimeAsync(1); + expect(t.run).toHaveBeenCalledTimes(2); + expect(idleWorkSnapshot().active).toBe(0); + next = null; + await vi.advanceTimersByTimeAsync(1000); + expect(t.run).toHaveBeenCalledTimes(3); + expect(s.coordinator.nextWakeAt()).toBeNull(); + }); it("does not postpone an already committed wake when another producer starts writing", async () => { const s = setup(), t = task(); await s.coordinator.register(DELIVERY_QUEUES.feedback, t).ready; diff --git a/server/src/__tests__/email-channels.integration.test.ts b/server/src/__tests__/email-channels.integration.test.ts index adcdda01844..c15499e947b 100644 --- a/server/src/__tests__/email-channels.integration.test.ts +++ b/server/src/__tests__/email-channels.integration.test.ts @@ -199,7 +199,9 @@ describe("AgentMail durable email pipeline", () => { expect(await db.select().from(authUsers).where(eq(authUsers.id, "email-board"))).toHaveLength(1); }); - async function fixture(mode: "websocket" | "webhook" = "webhook", storage?: StorageService) { + async function fixture(mode: "websocket" | "webhook" = "webhook", storage?: StorageService, + beforeSetup?: (input: { fetcher: typeof fetch; wakeup: ReturnType }) => Promise, + ) { const companyId = randomUUID(), agentId = randomUUID(), endpointId = randomUUID(); @@ -312,6 +314,7 @@ describe("AgentMail durable email pipeline", () => { storage, }); services.push(service); + await beforeSetup?.({ fetcher, wakeup }); await service.setup( companyId, { @@ -374,6 +377,73 @@ describe("AgentMail durable email pipeline", () => { setWebhookError: (status: number) => { webhookError = status; }, }; } + it("activates an empty running worker from another service and drains committed inbound and outbound work", async () => { + // Connector setup and tool calls construct short-lived service objects. + // Their committed writes must wake the app-owned worker sharing this DB. + let running!: EmailChannelService; + const f = await fixture("webhook", undefined, async ({ fetcher, wakeup }) => { + running = emailChannelService(db, { heartbeat: { wakeup }, fetch: fetcher }); + services.push(running); + await running.start(); + const select = vi.spyOn(db, "select"); + await new Promise(resolve => setTimeout(resolve, 1200)); + expect(select).not.toHaveBeenCalled(); + select.mockRestore(); + }); + await vi.waitFor(async () => { + const [config] = await db.select().from(emailEndpoints).where(eq(emailEndpoints.endpointId, f.endpointId)); + expect(config.lastSyncAt).not.toBeNull(); + }, { timeout: 5000 }); + await running.tick(); + await f.service.control(f.endpointId, "pause", { userId: "email-board" }); + await f.service.control(f.endpointId, "resume", { userId: "email-board" }); + const message = f.message(); + f.messages.set(message.message_id, message); + await f.service.admit(await f.service.getEndpoint(f.endpointId), { + event_type: "message.received", message, + }); + await vi.waitFor(() => expect(f.wakeup).toHaveBeenCalledTimes(1), { timeout: 5000 }); + const [parent] = await db.select().from(issues).where(eq(issues.companyId, f.companyId)); + const input = emailSendSchema.parse({ endpointId: f.endpointId, parentIssueId: parent.id, + to: ["recipient@example.test"], subject: "Wake on send", text: "Hello", idempotencyKey: randomUUID() }); + await f.service.queueSend(f.companyId, input, { userId: "email-board" }); + await vi.waitFor(async () => expect((await f.service.publication(input.idempotencyKey, f.companyId)).outcome).toBe("sent"), { timeout: 5000 }); + expect(f.sends).toHaveLength(1); + await running.tick(); + await f.service.control(f.endpointId, "pause", { userId: "email-board" }); + await new Promise(resolve => setTimeout(resolve, 100)); + const select = vi.spyOn(db, "select"); + await new Promise(resolve => setTimeout(resolve, 1200)); + expect(select).not.toHaveBeenCalled(); + }); + + it("restores a retry deadline without polling replies blocked behind that send", async () => { + const f = await fixture(); + const message = f.message("received", "outbound-thread"); + await f.receive(message); + const [conversation] = await db.select().from(chatConversations).where(eq(chatConversations.endpointId, f.endpointId)); + const input = emailSendSchema.parse({ endpointId: f.endpointId, conversationId: conversation.id, + replyToMessageId: message.message_id, text: "First reply", idempotencyKey: randomUUID() }); + await f.service.queueSend(f.companyId, input, { userId: "email-board" }); + const second = { ...input, text: "Second reply", idempotencyKey: randomUUID() }; + await f.service.queueSend(f.companyId, second, { userId: "email-board" }); + // Simulate a previous process persisting a provider retry deadline. The + // second reply has no deadline but cannot overtake this first reply. + await db.update(chatPublications).set({ state: "retry", nextAttemptAt: new Date(Date.now() + 5000) }) + .where(eq(chatPublications.id, input.idempotencyKey)); + await f.service.start(); + expect(f.sends).toHaveLength(0); + const select = vi.spyOn(db, "select"); + await new Promise(resolve => setTimeout(resolve, 1100)); + expect(select).not.toHaveBeenCalled(); + expect(f.sends).toHaveLength(0); + await vi.waitFor(() => expect(f.sends).toHaveLength(2), { timeout: 8000 }); + await f.service.tick(); + expect(f.sends.map(send => send.key)).toEqual([input.idempotencyKey, second.idempotencyKey]); + for (const id of [input.idempotencyKey, second.idempotencyKey]) + expect((await f.service.publication(id, f.companyId)).outcome).toBe("sent"); + }); + it("admits signed webhooks through the durable queue and rejects a valid signature for another inbox", async () => { const f = await fixture(); const endpoint = await f.service.getEndpoint(f.endpointId); diff --git a/server/src/__tests__/email-idle-work.test.ts b/server/src/__tests__/email-idle-work.test.ts new file mode 100644 index 00000000000..cd871b8d487 --- /dev/null +++ b/server/src/__tests__/email-idle-work.test.ts @@ -0,0 +1,81 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { Db } from "@paperclipai/db"; +import { installDatabaseWorkSignals } from "../../../packages/db/src/work-signals.js"; +import { emailChannelService } from "../services/email-channels.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "../services/delivery-work-notifications.js"; +import { idleWorkSnapshot } from "../services/task-admission.js"; + +const services: ReturnType[] = []; +afterEach(async () => { + for (const service of services.splice(0)) await service.shutdown(); + vi.useRealTimers(); +}); +function fixture() { + vi.useFakeTimers(); + const select = vi.fn(() => ({ from: () => ({ where: async () => [] }) })); + const execute = vi.fn(async () => [{ xid: "42", status: "aborted" }]); + const db = installDatabaseWorkSignals({ select, execute, + async transaction(callback: (tx: any) => Promise) { + return callback({ execute, transaction: db.transaction }); + }, + }); + let enabled = true; + const service = emailChannelService(db as unknown as Db, { + heartbeat: { wakeup: vi.fn() }, + isBackgroundWorkEnabled: () => enabled, + isReconciliationEnabled: () => true, + }); + services.push(service); + return { db, select, service, enable: (value: boolean) => { enabled = value; } }; +} + +describe("email idle work", () => { + it("scans at startup, then leaves an unconfigured stack with zero timers and queries", async () => { + const f = fixture(); + await f.service.start(); + expect(f.select).toHaveBeenCalledTimes(1); + await vi.advanceTimersByTimeAsync(3_600_000); + expect(f.select).toHaveBeenCalledTimes(1); + expect(vi.getTimerCount()).toBe(0); + }); + it("wakes on an outer transaction commit from a separate producer, never an inner savepoint", async () => { + const f = fixture(); + await f.service.start(); + await f.db.transaction(async tx => { + await tx.transaction(async (inner: object) => notifyDeliveryWork(inner, DELIVERY_QUEUES.email)); + expect(f.select).toHaveBeenCalledTimes(1); + }); + await vi.advanceTimersByTimeAsync(1); + expect(f.select).toHaveBeenCalledTimes(2); + expect(vi.getTimerCount()).toBe(0); + expect(idleWorkSnapshot().active).toBe(0); + }); + it("retains startup and committed work across idle drain without SQL or dispatch", async () => { + const f = fixture(); + f.enable(false); + await f.service.start(); + await f.db.transaction(tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.email)); + await vi.advanceTimersByTimeAsync(60_000); + expect(f.select).not.toHaveBeenCalled(); + expect(idleWorkSnapshot().active).toBe(0); + f.enable(true); + await vi.advanceTimersByTimeAsync(1001); + expect(f.select).toHaveBeenCalledTimes(1); + expect(vi.getTimerCount()).toBe(0); + }); + it("retries a failed startup scan and unsubscribes on shutdown", async () => { + const f = fixture(); + const warning = vi.spyOn(process, "emitWarning").mockImplementation(() => {}); + f.select.mockImplementationOnce(() => { throw new Error("database unavailable"); }); + await f.service.start(); + await vi.advanceTimersByTimeAsync(1001); + expect(f.select).toHaveBeenCalledTimes(2); + expect(vi.getTimerCount()).toBe(0); + await f.service.shutdown(); + await f.db.transaction(tx => notifyDeliveryWork(tx, DELIVERY_QUEUES.email)); + await vi.advanceTimersByTimeAsync(60_000); + expect(f.select).toHaveBeenCalledTimes(2); + expect(vi.getTimerCount()).toBe(0); + warning.mockRestore(); + }); +}); diff --git a/server/src/__tests__/voice-session-store.integration.test.ts b/server/src/__tests__/voice-session-store.integration.test.ts index 9f41a9bae6c..e547082a20c 100644 --- a/server/src/__tests__/voice-session-store.integration.test.ts +++ b/server/src/__tests__/voice-session-store.integration.test.ts @@ -1,3 +1,4 @@ +import { issueThreadInteractionService } from "../services/issue-thread-interactions.js"; import { readFile } from "node:fs/promises"; import { join } from "node:path"; import { documentService } from "../services/documents.js"; @@ -6,7 +7,7 @@ import { VOICE_RESULT_NOTIFICATION } from "@paperclipai/shared"; import { createHash, createHmac, randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { afterAll, beforeAll, describe, expect, it, vi } from "vitest"; -import { chatActions, environments, chatVoiceInboundCalls, chatVoicePhoneLines, chatVoiceReports, heartbeatRuns, 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 { chatActions, principalPermissionGrants, environments, chatVoiceInboundCalls, chatVoicePhoneLines, chatVoiceReports, heartbeatRuns, 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"; import { instanceSettingsService } from "../services/instance-settings.js"; import { chatChannelService } from "../services/chat-channels.js"; @@ -22,7 +23,7 @@ import { liveVoiceExecutionGuidance } from "../services/voice/voice-execution-gu import { buildPaperclipRuntimeMcpServers } from "../services/heartbeat.js"; import { createToolGatewayService } from "../services/tool-gateway.js"; import { initializeRunIdentity } from "../services/run-identity.js"; -import { spekoToolsForSession, executeSpekoVoiceTool } from "../services/voice/speko-agent-tools.js"; +import { syncSpekoVoiceTools, spekoToolsForSession, executeSpekoVoiceTool } from "../services/voice/speko-agent-tools.js"; const support = await getEmbeddedPostgresTestSupport(); (support.supported ? describe : describe.skip)("durable Speko voice sessions", () => { let db: ReturnType; @@ -229,6 +230,20 @@ const support = await getEmbeddedPostgresTestSupport(); expect(await rejoin(otherCaller)).toMatchObject({ status: "pending", updates: [] }); }); + it.each(["dispatching", "unknown", "completed"])("does not recollect a prior call's %s delivery or accepted prefix on rejoin", async status => { + const f = await fixture(), publication = await f.publication(); + await f.store.enqueuePublication(f.companyId, publication.id); + const [reply] = await db.select().from(chatVoiceReplies).where(eq(chatVoiceReplies.sessionId, f.sessionId)); + await db.insert(chatActions).values({companyId: f.companyId, endpointId: f.endpointId, conversationId: f.conversationId, + kind: "speko_voice_reply_push", providerActionId: `voice_reply_push:${reply.id}`, status, + payload: {sessionId: f.sessionId, replyId: reply.id, publicationId: publication.id, partIndex: 0, partCount: 2, questionNotification: false}}); + await db.update(chatVoiceSessions).set({state: "ended", endedAt: new Date()}).where(eq(chatVoiceSessions.id, f.sessionId)); + const reserved = await f.store.reserve({...f.request, idempotencyKey: randomUUID()}); + await db.update(chatVoiceSessions).set({state: "active", providerSessionId: randomUUID()}).where(eq(chatVoiceSessions.id, reserved.session.id)); + expect(await f.store.notification(f.companyId, reserved.session.id, f.callerId)).toBeNull(); + await f.store.enqueuePublication(f.companyId, publication.id); + expect(await db.select().from(chatVoiceReplies).where(eq(chatVoiceReplies.sessionId, reserved.session.id))).toHaveLength(0); + }); it("marks media active only after a valid session-scoped provider request", async () => { const f = await fixture(); await db.update(chatVoiceSessions).set({ state: "connecting" }).where(eq(chatVoiceSessions.id, f.sessionId)); @@ -854,6 +869,21 @@ const support = await getEmbeddedPostgresTestSupport(); 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("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"}); + const taskId = f.call.intakeIssueId!; + expect(await liveVoiceExecutionGuidance(db, {companyId: f.companyId, issueId: taskId, agentId: f.agentId})).toContain("Do not use ask_user_questions"); + for (const actor of [{agentId: f.agentId}, {systemId: "native-status-committer"}]) { + await expect(issueThreadInteractionService(db).create({companyId: f.companyId, id: taskId}, { + kind: "ask_user_questions", continuationPolicy: "wake_assignee", payload: {version: 1, + questions: [{id: "topic", prompt: "Which topic?", selectionMode: "single", required: true, options: [{id: "public", label: "Public inquiry"}]}]}, + }, actor)).rejects.toMatchObject({status: 422, details: {code: "voice_guest_use_task_comment"}}); + } + expect(await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, taskId))).toHaveLength(0); + expect(await f.tool("submit_request", {text: "Make it about shipping"})).toMatchObject({status: "accepted", authorization: "guest_intake"}); + expect(await db.select().from(chatVoiceToolCalls).where(eq(chatVoiceToolCalls.sessionId, f.call.sessionId!))).toHaveLength(2); + }); it("retires guest authority after an assignment or line permission change", async () => { const f = await inboundFixture(true); await f.tool("submit_request", {text: "Please record a public inquiry"}); @@ -1121,6 +1151,9 @@ const support = await getEmbeddedPostgresTestSupport(); async function phoneToolFixture() { const f = await nativeServiceFixture(); await instanceSettingsService(db).updateExperimental({ enableChatConnectors: true }); + const [endpoint] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, f.endpointId)); + await db.insert(principalPermissionGrants).values({companyId: f.companyId, principalType: "user", principalId: f.callerId, permissionKey: "agents:configure"}); + await db.transaction(tx => syncSpekoVoiceTools(tx, endpoint, f.callerId)); await f.service.saveCallbackPreference(f.companyId, f.endpointId, f.request.caller, { phoneNumber: "+12015551234", enabled: true }); const runId = randomUUID(); await db.insert(heartbeatRuns).values({ id: runId, companyId: f.companyId, agentId: f.agentId, status: "running", contextSnapshot: { issueId: f.issueId } }); @@ -1129,6 +1162,18 @@ const support = await getEmbeddedPostgresTestSupport(); const gatewaySession = await gateway.createSession({ companyId: f.companyId, agentId: f.agentId, runId, issueId: f.issueId }); return { ...f, runId, gateway, gatewaySession }; } + it("keeps personal callback preferences separate from authorized agent tool installation", async () => { + const f = await nativeServiceFixture(); + const [endpoint] = await db.select().from(chatEndpoints).where(eq(chatEndpoints.id, f.endpointId)); + for (const enabled of [false, true]) await f.service.saveCallbackPreference(f.companyId, f.endpointId, f.request.caller, {phoneNumber: "+12015551234", enabled}); + expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, f.connectionId))).toHaveLength(0); + expect(await db.select().from(toolProfileBindings).where(eq(toolProfileBindings.targetId, f.agentId))).toHaveLength(0); + await expect(db.transaction(tx => syncSpekoVoiceTools(tx, endpoint, f.callerId))).rejects.toMatchObject({status: 403}); + expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, f.connectionId))).toHaveLength(0); + await db.insert(principalPermissionGrants).values({companyId: f.companyId, principalType: "user", principalId: f.callerId, permissionKey: "agents:configure"}); + await db.transaction(tx => syncSpekoVoiceTools(tx, endpoint, f.callerId)); + expect(await db.select().from(toolConnectionInstalls).where(eq(toolConnectionInstalls.connectionId, f.connectionId))).toHaveLength(1); + }); it("delivers Speko guidance to existing agents only while the connection remains assigned and enabled", async () => { const f = await phoneToolFixture(); const binding = { companyId: f.companyId, agentId: f.agentId }; diff --git a/server/src/app.ts b/server/src/app.ts index faa0b75ff1a..bce7324803c 100644 --- a/server/src/app.ts +++ b/server/src/app.ts @@ -652,6 +652,7 @@ export async function createApp( // mutation guard. The Chat SDK adapter verifies the provider signature // before Paperclip persists or acts on any event. const emailChannels = emailChannelService(db, { + isReconciliationEnabled: () => !isWarmStandby(), isBackgroundWorkEnabled: () => !isWarmStandby() && !isIdleTaskDrainActive(), heartbeat: connectionIntentHeartbeat, storage: opts.storageService, diff --git a/server/src/services/chat-channels.ts b/server/src/services/chat-channels.ts index 7a2a599eb9d..504310c5a6b 100644 --- a/server/src/services/chat-channels.ts +++ b/server/src/services/chat-channels.ts @@ -1,3 +1,4 @@ +import { syncSpekoVoiceTools } from "./voice/speko-agent-tools.js"; import { configureSpekoSessionTools } from "./voice/speko-tool-setup.js"; import { voiceSessionService } from "./voice/voice-session-service.js"; import { createSpekoProvider } from "./voice/speko-provider.js"; @@ -9642,6 +9643,10 @@ export function chatChannelService(db: Db, options: ChatChannelServiceOptions) { .for("update") .then((rows) => rows[0] ?? null); if (!current) throw notFound("Chat endpoint not found"); + if (endpoint.provider === "speko") { + if (!actorUserId) throw forbidden("An authenticated connection owner is required to install phone tools"); + await syncSpekoVoiceTools(tx, endpoint, actorUserId, true, options.allowLocalVoiceBoard === true); + } const observedSlackUrl = (current.setup as InternalSetupState).slackCallbackSurfaces?.events?.url; const preserveSlackVerification = current.setup.slackSetupMethod === "automatic" && (current.setup as InternalSetupState).slackVerificationSigningFingerprint === createHash("sha256").update(credentials.signingSecret ?? "").digest("hex") diff --git a/server/src/services/delivery-work-coordinator.ts b/server/src/services/delivery-work-coordinator.ts index 34a198671ba..0272fc2ed72 100644 --- a/server/src/services/delivery-work-coordinator.ts +++ b/server/src/services/delivery-work-coordinator.ts @@ -22,6 +22,8 @@ export function createDeliveryWorkCoordinator(input: { retryMs: number; run: (signal: AbortSignal) => Promise; hasPending: () => Promise; + // Optional maintenance/retry deadline restored from durable state. + nextRunAt?: () => number | null; }) { if (stopped) throw new Error("Delivery coordinator is stopped"); if (workers.has(queue)) throw new Error(`Delivery worker already registered: ${queue}`); @@ -51,6 +53,8 @@ export function createDeliveryWorkCoordinator(input: { .then(() => workerStopped || !input.canRun() ? undefined : task.run(attempt.signal)).then(() => workerStopped ? false : task.hasPending()).then(pending => { if (pending || databaseWorkPending(input.owner, queue)) schedule(task.retryMs); else { finishIntent?.(); finishIntent = undefined; } + const next = task.nextRunAt?.(); + if (next != null) schedule(Math.max(0, next - Date.now())); }).catch(error => { schedule(task.retryMs); // Logging must never turn a recoverable sweep failure into an diff --git a/server/src/services/delivery-work-notifications.ts b/server/src/services/delivery-work-notifications.ts index 14b67085d1d..d9696da5cf2 100644 --- a/server/src/services/delivery-work-notifications.ts +++ b/server/src/services/delivery-work-notifications.ts @@ -2,6 +2,7 @@ import { signalDatabaseWork, subscribeDatabaseWork } from "@paperclipai/db"; /** Topics for existing durable queues; register intent before their writes. */ export const DELIVERY_QUEUES = { + email: "email-channels", feedback: "feedback-exports", chatCompletion: "chat-completions", connection: "connection-continuations", diff --git a/server/src/services/email-channels.ts b/server/src/services/email-channels.ts index 62db025fd6c..830d5f921f9 100644 --- a/server/src/services/email-channels.ts +++ b/server/src/services/email-channels.ts @@ -1,3 +1,5 @@ +import { createDeliveryWorkCoordinator } from "./delivery-work-coordinator.js"; +import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js"; import { HttpError } from "../errors.js"; import { createHash, randomUUID } from "node:crypto"; import WebSocket from "ws"; @@ -77,6 +79,8 @@ type Tx = Parameters[0]>[0]; export interface EmailChannelOptions { /** Suppress periodic database work while an unclaimed Cloud app stands by. */ isBackgroundWorkEnabled?: () => boolean; + /** Allow transaction outcome checks during idle drain, but not warm standby. */ + isReconciliationEnabled?: () => boolean; heartbeat: Pick, "wakeup">; storage?: StorageService; publicBaseUrl?: string; @@ -130,7 +134,12 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { let stopped = false; let ticking = false; let activeTick: Promise | null = null; - let timer: ReturnType | undefined; + let coordinator: ReturnType | undefined; + let worker: ReturnType["register"]> | undefined; + let nextWorkAt: number | null = null; + function needWorkAt(at: number) { + nextWorkAt = Math.min(nextWorkAt ?? Infinity, Math.max(Date.now() + 1000, at)); + } async function getEndpoint(id: string) { const [row] = await db @@ -881,6 +890,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { } const now = new Date(); await db.transaction(async (tx) => { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.email); await tx .update(emailEndpoints) .set({ @@ -909,7 +919,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { return summary(await getEndpoint(endpoint.id)); }); if (!result) throw conflict("Inbox setup is already running"); - if (timer) void tick().catch(() => {}); return result; } @@ -919,22 +928,24 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { if (!event) return; if (event.inbox_id !== endpoint.botExternalId) throw forbidden("Email event belongs to a different inbox"); - await db - .insert(chatDeliveries) - .values({ - companyId: endpoint.companyId, - endpointId: endpoint.id, - providerEventId: event.eventId, - deduplicationKey: `${event.kind}:${event.message_id}`, - eventKind: "message", - normalizedEvent: event, - }) - .onConflictDoNothing(); - await db - .update(chatEndpoints) - .set({ lastEventAt: new Date() }) - .where(eq(chatEndpoints.id, endpoint.id)); - if (timer) void tick().catch(() => {}); + await db.transaction(async (tx) => { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.email); + await tx + .insert(chatDeliveries) + .values({ + companyId: endpoint.companyId, + endpointId: endpoint.id, + providerEventId: event.eventId, + deduplicationKey: `${event.kind}:${event.message_id}`, + eventKind: "message", + normalizedEvent: event, + }) + .onConflictDoNothing(); + await tx + .update(chatEndpoints) + .set({ lastEventAt: new Date() }) + .where(eq(chatEndpoints.id, endpoint.id)); + }); } async function webhook( publicId: string, @@ -1550,6 +1561,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { if (!reply) throw badRequest("Reply target is not in this inbox conversation"); } + await notifyDeliveryWork(tx, DELIVERY_QUEUES.email); await tx.insert(chatPublications).values({ id: input.idempotencyKey, companyId, @@ -1571,7 +1583,6 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { await audit(endpoint, "email.queued", actor, { publicationId: input.idempotencyKey, }); - if (timer) void tick().catch(() => {}); return publication(input.idempotencyKey, companyId); } async function publication( @@ -1968,6 +1979,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { .update(emailEndpoints) .set({ lastSyncAt: null }) .where(eq(emailEndpoints.endpointId, endpoint.id)); + worker?.wake(); } else await admit(endpoint, value); })().catch(async () => { await markError( @@ -1988,6 +2000,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { const delay = Math.min(60_000, (backoff.get(endpoint.id) ?? 1000) * 2); backoff.set(endpoint.id, delay); reconnectAt.set(endpoint.id, Date.now() + delay); + worker?.wake(); void db .delete(chatEndpointLeases) .where( @@ -2056,6 +2069,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { async function runTick() { if (ticking || stopped) return; ticking = true; + nextWorkAt = null; try { const endpoints = await db .select() @@ -2096,7 +2110,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { ne(chatPublications.state, "delivery_unknown"), ), ) - .orderBy(asc(chatPublications.createdAt)) + .orderBy(asc(chatPublications.createdAt), asc(chatPublications.id)) .limit(25); // Each conversation is serial, while independent inbox threads can make progress. const firstSends = [ @@ -2199,7 +2213,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { ); if ( !config.lastSyncAt || - Date.now() - config.lastSyncAt.getTime() > 60_000 + Date.now() - config.lastSyncAt.getTime() >= 60_000 ) await withLease( endpoint, @@ -2208,7 +2222,40 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { }, "email-catchup", ); + // Catch-up is a real scheduled obligation; an empty queue is not. + const refreshed = await getConfig(endpoint.id); + needWorkAt((refreshed.lastSyncAt?.getTime() ?? 0) + 60_000); + if (refreshed.receiveMode === "websocket" && !sockets.has(endpoint.id)) + needWorkAt(reconnectAt.get(endpoint.id) ?? Date.now() + 1000); + const [inbound] = await db + .select({ at: sql`min(coalesce(${chatDeliveries.nextAttemptAt}, now()))` }) + .from(chatDeliveries) + .where(and( + eq(chatDeliveries.endpointId, endpoint.id), + inArray(chatDeliveries.state, ["received", "processing", "retry"]), + )); + // A later reply cannot run ahead of its conversation's first send. + // Its null deadline must not turn a delayed retry into 1s polling. + const sendHeads = db + .selectDistinctOn([chatPublications.conversationId], { + nextAttemptAt: chatPublications.nextAttemptAt, + }) + .from(emailSends) + .innerJoin(chatPublications, eq(chatPublications.id, emailSends.publicationId)) + .where(and( + eq(emailSends.endpointId, endpoint.id), + inArray(emailSends.outcome, ["queued", "uncertain"]), + ne(chatPublications.state, "delivery_unknown"), + )) + .orderBy(asc(chatPublications.conversationId), asc(chatPublications.createdAt), asc(chatPublications.id)) + .as("email_send_heads"); + const [outbound] = await db + .select({ at: sql`min(coalesce(${sendHeads.nextAttemptAt}, now()))` }) + .from(sendHeads); + for (const pending of [inbound, outbound]) + if (pending?.at) needWorkAt(new Date(pending.at).getTime()); } catch (e) { + needWorkAt(Date.now() + 1000); await markError(endpoint, diagnostic(e)); } }), @@ -2219,6 +2266,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { } async function stopEndpoint(endpoint: Endpoint) { await db.transaction(async (tx) => { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.email); await tx .select() .from(chatEndpoints) @@ -2319,6 +2367,7 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { await removeUnusedSecret(secretId); } await db.transaction(async (tx) => { + await notifyDeliveryWork(tx, DELIVERY_QUEUES.email); await tx .update(chatEndpoints) .set({ @@ -2642,17 +2691,28 @@ export function emailChannelService(db: Db, options: EmailChannelOptions) { }; }, start: () => { - if (!timer) { - timer = setInterval(() => { - void tick().catch(() => {}); - }, 1000); - timer.unref(); - void tick().catch(() => {}); - } + if (coordinator || stopped) return; + coordinator = createDeliveryWorkCoordinator({ + owner: db, + canRun: () => options.isBackgroundWorkEnabled?.() !== false, + canReconcile: () => options.isReconciliationEnabled?.() ?? (options.isBackgroundWorkEnabled?.() !== false), + onError: (error) => process.emitWarning(`Email background work failed: ${diagnostic(error)}`), + }); + worker = coordinator.register(DELIVERY_QUEUES.email, { + retryMs: 1000, + run: tick, + // Retries and maintenance have deadlines; only unresolved writes need + // the coordinator's pending-intent hold, not a configured idle inbox. + hasPending: async () => false, + nextRunAt: () => options.isBackgroundWorkEnabled?.() === false + ? Date.now() + 1000 + : nextWorkAt, + }); + return worker.ready; }, shutdown: async () => { stopped = true; - clearInterval(timer); + await coordinator?.stop(); await activeTick; const heldSockets = [...sockets.entries()]; sockets.clear(); diff --git a/server/src/services/issue-thread-interactions.ts b/server/src/services/issue-thread-interactions.ts index 58555ccb48d..729bf84f75b 100644 --- a/server/src/services/issue-thread-interactions.ts +++ b/server/src/services/issue-thread-interactions.ts @@ -26,6 +26,7 @@ import { import type { Db } from "@paperclipai/db"; import { agents, + chatVoiceSessions, authUsers, companySecretProposals, companies, @@ -3674,6 +3675,15 @@ export function issueThreadInteractionService( lockForUpdate: true, }); } + // An unverified phone caller has no authenticated human identity. + // Their clarifications use the ordinary task-comment/follow-up queue; + // a protected native question would otherwise wait indefinitely. + if (data.kind === "ask_user_questions" && !actor.userId) { + const [guest] = await tx.select({id: chatVoiceSessions.id}).from(chatVoiceSessions) + .where(and(eq(chatVoiceSessions.companyId, issue.companyId), eq(chatVoiceSessions.issueId, issue.id), + eq(chatVoiceSessions.callerAuthority, "guest_intake"))).limit(1); + if (guest) throw unprocessable("Ask this unverified caller a clarification in a task comment; submit_request will deliver their spoken follow-up. Protected human-input questions require authenticated access.", {code: "voice_guest_use_task_comment"}); + } const [row] = await tx .insert(issueThreadInteractions) .values({ diff --git a/server/src/services/voice/speko-agent-tools.ts b/server/src/services/voice/speko-agent-tools.ts index 994f8186891..669a70a0c56 100644 --- a/server/src/services/voice/speko-agent-tools.ts +++ b/server/src/services/voice/speko-agent-tools.ts @@ -1,6 +1,7 @@ import { createHash } from "node:crypto"; import { and, eq, isNull, sql } from "drizzle-orm"; import { forbidden, HttpError } from "../../errors.js"; +import { authorizationService } from "../authorization.js"; import { captureRunIdentity } from "../run-identity.js"; import { chatVoiceCallbacks, instanceUserRoles, companyMemberships } from "@paperclipai/db"; import type { VoiceCaller } from "./voice-session-store.js"; @@ -56,7 +57,15 @@ export async function syncSpekoVoiceTools( endpoint: typeof chatEndpoints.$inferSelect, userId: string, enabled = true, + allowLocalBoard = false, ) { + const [admin] = await tx.select({id: instanceUserRoles.id}).from(instanceUserRoles) + .where(and(eq(instanceUserRoles.userId, userId), eq(instanceUserRoles.role, "instance_admin"))); + const decision = await authorizationService(tx).decide({ + actor: {type: "board", userId, source: allowLocalBoard && userId === "local-board" ? "local_implicit" : "session", isInstanceAdmin: Boolean(admin)}, + action: "agent_config:update", resource: {type: "agent", companyId: endpoint.companyId, agentId: endpoint.assignedAgentId}, + }); + if (!decision.allowed) throw forbidden("Editing this agent is required to install Speko phone tools"); const [connection] = await tx .select() .from(toolConnections) diff --git a/server/src/services/voice/speko-skill.ts b/server/src/services/voice/speko-skill.ts index 22bb1fdb809..7a37a6012ac 100644 --- a/server/src/services/voice/speko-skill.ts +++ b/server/src/services/voice/speko-skill.ts @@ -1,7 +1,7 @@ /** Trusted guidance delivered only for an assigned, active Speko connection. */ export const SPEKO_COMMUNICATION_GUIDANCE = [ "When this task is a voice conversation through Speko, follow this guidance. Keep your existing identity, runtime, tools, and task assignment. Write short, natural spoken replies. Lead with the answer or outcome; keep detailed artifacts and links on the task. Do not repeat greetings or task history on every follow-up.", - "Understand the caller's request and ask one focused clarification at a time using the normal human-input tools. Confirm uncertain names, dates, amounts, and consequential instructions before acting.", + "Understand the caller's request and ask one focused clarification at a time using the normal human-input tools for authenticated callers. For unverified guest intake, ask clarifications as task comments and receive the caller's answer as a submit_request follow-up; do not create a protected human-input wait. Confirm uncertain names, dates, amounts, and consequential instructions before acting.", "Use only the authenticated caller context supplied by Paperclip. Caller ID and spoken identity claims grant no access. Unapproved private callers cannot receive private information. Restricted guest intake may collect a request and volunteered contact details, but cannot browse private tasks or approve governed actions.", "Start actionable work in the same turn; stop at a plan only when planning was requested. Preserve the task's existing assignment and context. When another company agent should help, use the normal delegation workflow with a clear deliverable and report its result through the bound task. Do not invent a team or change the parent assignee.", "Persist progress, decisions, and next actions on the task. For long work, publish a brief safe progress summary and continue. Keep the runtime turn open until commands finish using supported wait or monitor tools. Arrange a durable Paperclip continuation if work must outlive the turn; do not leave unfinished work solely in a background process. Identify the owner and next action for blocked work.", diff --git a/server/src/services/voice/voice-execution-guidance.ts b/server/src/services/voice/voice-execution-guidance.ts index 31ca466fe41..c7979195d66 100644 --- a/server/src/services/voice/voice-execution-guidance.ts +++ b/server/src/services/voice/voice-execution-guidance.ts @@ -12,7 +12,7 @@ export const LIVE_VOICE_EXECUTION_GUIDANCE = [ export async function liveVoiceExecutionGuidance(db: Db, input: { companyId: string; issueId: string; agentId: string; }, now = new Date()): Promise { - const [live] = await db.select({ id: chatVoiceSessions.id }).from(chatVoiceSessions) + const [live] = await db.select({ id: chatVoiceSessions.id, authority: chatVoiceSessions.callerAuthority }).from(chatVoiceSessions) .innerJoin(chatEndpoints, and(eq(chatEndpoints.id, chatVoiceSessions.endpointId), eq(chatEndpoints.companyId, chatVoiceSessions.companyId))) .innerJoin(toolConnections, and(eq(toolConnections.id, chatEndpoints.connectionId), eq(toolConnections.companyId, chatEndpoints.companyId))) .where(and( @@ -27,5 +27,7 @@ export async function liveVoiceExecutionGuidance(db: Db, input: { and ${chatVoiceToolCalls.sessionId} = ${chatVoiceSessions.id} and ${chatVoiceToolCalls.tool} = 'submit_request' and ${chatVoiceToolCalls.deliveryId} is not null)`, )).limit(1); - return live ? LIVE_VOICE_EXECUTION_GUIDANCE : null; + return live ? [LIVE_VOICE_EXECUTION_GUIDANCE, live.authority === "guest_intake" + ? "This caller is unverified. Ask any clarification as a brief task comment and continue when submit_request brings their spoken follow-up. Do not use ask_user_questions or create a protected human-input wait. Guest answers cannot grant approval or access to private work." + : null].filter(Boolean).join("\n\n") : null; } diff --git a/server/src/services/voice/voice-inbound-service.ts b/server/src/services/voice/voice-inbound-service.ts index dc1975c9034..d59755ee848 100644 --- a/server/src/services/voice/voice-inbound-service.ts +++ b/server/src/services/voice/voice-inbound-service.ts @@ -183,7 +183,7 @@ export function voiceInboundService(db: Db, options: { const reviewPreset = {id: LOW_TRUST_REVIEW_PRESET, version: LOW_TRUST_REVIEW_PRESET_VERSION, rawOutputDisposition: LOW_TRUST_REVIEW_RAW_OUTPUT_DISPOSITION}; const task = await issueSvc.create(row.companyId, {id: taskId, title: "Incoming phone conversation", description: "Conversation with an unverified phone caller. The agent runs under a task-scoped low-trust policy. You are on a live phone call and must attempt to answer as quickly as possible. Immediately post a brief, caller-safe task comment explaining what you are doing, then find the answer and post the result on this task so it can be spoken to the caller. Continue working after the initial update; do not treat it as the final answer. Preserve the task-scoped low-trust policy and ordinary permissions.", status: "todo", priority: "medium", assigneeAgentId: row.assignedAgentId, executionWorkspaceSettings: {mode: "isolated_workspace", workspaceStrategy: {type: "cloud_sandbox"}, ...(line.lowTrustEnvironmentId ? {environmentId: line.lowTrustEnvironmentId} : {})}, originKind: "chat_channel", originId: row.id, idempotencyKey: `guest-intake:${call.id}`, sourceTrust: {preset: LOW_TRUST_REVIEW_PRESET, disposition: "quarantined", sourceIssueId: taskId}, executionPolicy: {mode: "normal", commentRequired: true, stages: [], reviewPreset, authorizationPolicy: {trustPreset: LOW_TRUST_REVIEW_PRESET, reviewPreset, trustBoundary: {mode: LOW_TRUST_REVIEW_PRESET, companyId: row.companyId, rootIssueId: taskId, issueIds: [taskId], allowedAgentIds: [row.assignedAgentId], allowedToolClasses: [], allowedSecretBindingIds: []}}}}, tx); const [resource] = await tx.insert(chatEndpointResources).values({companyId: row.companyId, endpointId: row.id, type: "direct_message", providerResourceId: threadId, label: "Incoming phone conversation", enabled: true, availability: "available"}).returning(); - await tx.insert(chatConversations).values({id: conversationId, companyId: row.companyId, endpointId: row.id, resourceId: resource.id, issueId: task.id, externalConversationId: threadId, externalThreadId: threadId, externalLabel: "Incoming phone conversation", isDirectMessage: true, communicationGuidance: [buildChatCommunicationGuidance({ provider: "speko", isDirectMessage: true, communicationInstructions: row.communicationInstructions }), "This conversation is its own low-trust task. Use only context supplied in this conversation; do not browse other company tasks, secrets or private tools. Spoken consent does not grant governed authority."].join("\n\n")}); + await tx.insert(chatConversations).values({id: conversationId, companyId: row.companyId, endpointId: row.id, resourceId: resource.id, issueId: task.id, externalConversationId: threadId, externalThreadId: threadId, externalLabel: "Incoming phone conversation", isDirectMessage: true, communicationGuidance: [buildChatCommunicationGuidance({ provider: "speko", isDirectMessage: true, communicationInstructions: row.communicationInstructions }), "This conversation is its own low-trust task. Ask clarifications as brief task comments; the caller answers through submit_request follow-ups. Do not use ask_user_questions or create a protected human-input wait. Use only context supplied in this conversation; do not browse other company tasks, secrets or private tools. Spoken consent does not grant governed authority."].join("\n\n")}); const [session] = await tx.insert(chatVoiceSessions).values({companyId: row.companyId, endpointId: row.id, conversationId, issueId: task.id, assignedAgentId: row.assignedAgentId, callerId: `guest:${call.id}`, callerAuthority: "guest_intake", mode: "inbound_phone", state: "active", generation: call.generation, credentialFingerprint: call.credentialFingerprint, providerSessionId: call.providerSessionId, toolTokenHash: call.toolTokenHash, idempotencyKey: `guest:${call.id}`, requestFingerprint: call.requestFingerprint, createdAt: call.createdAt, expiresAt: call.expiresAt}).returning({id: chatVoiceSessions.id}); await tx.update(chatVoiceInboundCalls).set({intakeIssueId: task.id, sessionId: session.id, updatedAt: new Date()}).where(eq(chatVoiceInboundCalls.id, call.id)); await tx.insert(activityLog).values({companyId: row.companyId, actorType: "system", actorId: "speko-inbound", action: "voice.low_trust_call.started", entityType: "issue", entityId: task.id, details: {callId: call.id, sessionId: session.id}}); diff --git a/server/src/services/voice/voice-session-service.ts b/server/src/services/voice/voice-session-service.ts index dc01f72f2ae..59b99c6616d 100644 --- a/server/src/services/voice/voice-session-service.ts +++ b/server/src/services/voice/voice-session-service.ts @@ -13,7 +13,7 @@ import { documentService } from "../documents.js"; import { issueService } from "../issues.js"; import { createSpekoProvider, SpekoProviderError } from "./speko-provider.js"; import { serializeVoiceSession, voiceSessionStore, type VoiceCaller, type VoiceSessionRow } from "./voice-session-store.js"; -import { syncSpekoVoiceTools, registerSpekoVoiceRuntime } from "./speko-agent-tools.js"; +import { registerSpekoVoiceRuntime } from "./speko-agent-tools.js"; import { verifySpekoToolRequest } from "./speko-protocol.js"; import { VOICE_PROMPT, PHONE_VOICE_PROMPT, LOW_TRUST_PHONE_VOICE_PROMPT } from "./voice-prompts.js"; @@ -340,11 +340,10 @@ export function voiceSessionService(db: Db, options: { return row ? { phoneNumber: row.phoneNumber, enabled: row.enabled } : null; } async function saveCallbackPreference(companyId: string, endpointId: string, caller: VoiceCaller, preference: { phoneNumber: string; enabled: boolean }) { - const endpoint = await endpointFor(companyId, endpointId); + await endpointFor(companyId, endpointId); await db.transaction(async tx => { await store.authorizeCaller(tx, companyId, caller); await tx.insert(chatVoiceCallbacks).values({ companyId, endpointId, userId: caller.id, ...preference }).onConflictDoUpdate({ target: [chatVoiceCallbacks.companyId, chatVoiceCallbacks.endpointId, chatVoiceCallbacks.userId], set: { ...preference, updatedAt: new Date() } }); - await syncSpekoVoiceTools(tx, endpoint, caller.id); await tx.insert(activityLog).values({ companyId, actorType: "user", actorId: caller.id, action: "voice.callback.preference_updated", entityType: "chat_endpoint", entityId: endpointId, details: { enabled: preference.enabled } }); }); return preference; diff --git a/server/src/services/voice/voice-session-store.ts b/server/src/services/voice/voice-session-store.ts index d9ad570ace9..315c0f43a27 100644 --- a/server/src/services/voice/voice-session-store.ts +++ b/server/src/services/voice/voice-session-store.ts @@ -1,6 +1,6 @@ import { logger } from "../../middleware/logger.js"; import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto"; -import { and, asc, desc, eq, gte, inArray, isNull, or, sql } from "drizzle-orm"; +import { and, asc, desc, eq, gte, inArray, isNull, or, sql, type SQL } from "drizzle-orm"; import { activityLog, chatVoicePhoneLines, chatVoiceInboundCalls, chatVoiceCallbacks, chatEndpoints, chatConversations, chatDeliveries, chatPublications, chatVoiceSessions, chatVoiceToolCalls, chatVoiceReplies, companyMemberships, companySecrets, connectionGrants, connectionGrantMembers, toolConnectionInstalls, instanceUserRoles, issueThreadInteractions, issues, heartbeatRuns, toolConnections, type Db } from "@paperclipai/db"; import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared"; import type { ToolCredentialSecretRef, VoiceSession } from "@paperclipai/shared"; @@ -211,6 +211,21 @@ export function voiceSessionStore(db: Db, options: { allowLocalBoard: boolean; n }).returning({ id: chatDeliveries.id }); 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 + 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} + and s.endpoint_id = ${session.endpointId} and s.conversation_id = ${session.conversationId} + and s.issue_id = ${session.issueId} + and (r.delivered_at is not null or exists ( + select 1 from chat_actions a where a.company_id = r.company_id + and a.endpoint_id = s.endpoint_id and a.kind = 'speko_voice_reply_push' + and a.payload->>'replyId' = r.id::text + and (a.status in ('dispatching', 'unknown') or + (a.status = 'completed' and coalesce(a.payload->>'questionNotification', 'false') = 'false')) + )))`; + } async function collectMissedReplies(tx: VoiceTransaction, session: VoiceSessionRow) { // Only publications since this caller joined this exact conversation are // eligible. Transport acceptance in any prior call suppresses automatic @@ -224,11 +239,9 @@ export function voiceSessionStore(db: Db, options: { allowLocalBoard: boolean; n eq(chatPublications.conversationId, session.conversationId), eq(chatPublications.issueId, session.issueId), eq(chatPublications.state, "published"), gte(chatPublications.createdAt, first?.createdAt ?? session.createdAt), sql`(coalesce(${chatPublications.payload}->>'progressState', '') = '' or ${chatPublications.payload}->>'interactionId' is not null)`, - sql`not 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 = ${chatPublications.id} - and (s.id = ${session.id} or (s.caller_id = ${session.callerId} - and s.conversation_id = ${session.conversationId} and r.delivered_at is not null)))`, + sql`not exists (select 1 from chat_voice_replies r where r.company_id = ${session.companyId} + and r.publication_id = ${chatPublications.id} and r.session_id = ${session.id})`, + sql`not (${priorCallDeliveryBarrier(session, sql`${chatPublications.id}`)})`, )).orderBy(asc(chatPublications.createdAt), asc(chatPublications.id)).limit(100); let cursor = session.replyCursor; for (const publication of missing) { @@ -424,6 +437,9 @@ export function voiceSessionStore(db: Db, options: { allowLocalBoard: boolean; n const { session } = await authorizeSession(tx, companyId, candidate.id); const prior = await tx.select({ id: chatVoiceReplies.id }).from(chatVoiceReplies).where(and(eq(chatVoiceReplies.sessionId, session.id), eq(chatVoiceReplies.publicationId, publication.id))).then((rows) => rows[0]); if (prior) return; + const [priorCall] = await tx.select({blocked: priorCallDeliveryBarrier(session, publication.id)}) + .from(chatPublications).where(eq(chatPublications.id, publication.id)).limit(1); + if (priorCall?.blocked) return; const cursor = session.replyCursor + 1; await tx.insert(chatVoiceReplies).values({ companyId, sessionId: session.id, publicationId: publication.id, cursor }); await tx.update(chatVoiceSessions).set({ replyCursor: cursor, updatedAt: new Date() }).where(eq(chatVoiceSessions.id, session.id));