From 18f9383a8545f9a5138bc9b9c5820df1fafb88cc Mon Sep 17 00:00:00 2001 From: Dotta Date: Fri, 9 Oct 2026 15:30:55 -0500 Subject: [PATCH] test(voice): qualify phone reply pushes and preserve live probe evidence Co-Authored-By: Paperclip --- tests/speko-native/app.ts | 7 +++-- tests/speko-native/authenticated.spec.ts | 3 +- tests/speko-native/integrated.spec.ts | 5 ++++ tests/speko-native/live-browser.mjs | 9 ++++-- tests/speko-native/stub-provider.ts | 17 ++++++++++- tests/speko-voice-proof/browser-client.mjs | 2 +- tests/speko-voice-proof/live-client.mjs | 33 ++++++++++++++-------- 7 files changed, 55 insertions(+), 21 deletions(-) diff --git a/tests/speko-native/app.ts b/tests/speko-native/app.ts index b384dccf0ff..8154f6cce89 100644 --- a/tests/speko-native/app.ts +++ b/tests/speko-native/app.ts @@ -5,7 +5,7 @@ import { randomInt } from "node:crypto"; import { once } from "node:events"; import { createRequire } from "node:module"; import { setTimeout as delay } from "node:timers/promises"; -import { createDb, authUsers, instanceUserRoles, issueComments, issues, issueThreadInteractions, issueQuestionResponseDeliveries, chatVoiceInboundCalls, chatVoiceReports, chatVoiceSessions, chatVoiceReplies, chatVoiceToolCalls, chatDeliveries, chatPublications, heartbeatRuns, agentWakeupRequests } from "../../packages/db/src/index.js"; +import { createDb, authUsers, instanceUserRoles, issueComments, issues, issueThreadInteractions, issueQuestionResponseDeliveries, chatVoiceInboundCalls, chatVoiceReports, chatVoiceSessions, chatVoiceReplies, chatVoiceToolCalls, chatActions, chatDeliveries, chatPublications, heartbeatRuns, agentWakeupRequests } from "../../packages/db/src/index.js"; const home = process.env.PAPERCLIP_HOME!; const port = Number(process.env.SPEKO_NATIVE_PORT ?? 3449); const origin = `http://127.0.0.1:${port}`; @@ -114,7 +114,7 @@ async function writeEvidence() { if (evidenceWriting) return; evidenceWriting = true; try { - const [reports, incoming, sessions, replies, tools, deliveries, publications, runs, wakeups, comments, interactions, questionDeliveries] = await Promise.all([ + const [reports, incoming, sessions, replies, tools, deliveries, publications, runs, wakeups, comments, interactions, questionDeliveries, pushActions] = await Promise.all([ db.select({sessionId: chatVoiceReports.sessionId, companyId: chatVoiceReports.companyId, status: chatVoiceReports.status, costMicroUsd: chatVoiceReports.costMicroUsd, transcript: chatVoiceReports.transcript}).from(chatVoiceReports), db.select({id: chatVoiceInboundCalls.id, companyId: chatVoiceInboundCalls.companyId, endpointId: chatVoiceInboundCalls.endpointId, state: chatVoiceInboundCalls.state, sessionId: chatVoiceInboundCalls.sessionId}).from(chatVoiceInboundCalls), db.select({ id: chatVoiceSessions.id, issueId: chatVoiceSessions.issueId, providerSessionId: chatVoiceSessions.providerSessionId, mode: chatVoiceSessions.mode, state: chatVoiceSessions.state }).from(chatVoiceSessions), @@ -127,6 +127,7 @@ async function writeEvidence() { db.select({ id: issueComments.id, issueId: issueComments.issueId, body: issueComments.body, authorAgentId: issueComments.authorAgentId, createdByRunId: issueComments.createdByRunId }).from(issueComments), db.select().from(issueThreadInteractions), db.select().from(issueQuestionResponseDeliveries), + db.select().from(chatActions).where(eq(chatActions.kind, "speko_voice_reply_push")), ]); const runEvidence = runs.map(({ contextSnapshot, ...row }) => { const context = (contextSnapshot ?? {}) as Record; @@ -135,7 +136,7 @@ async function writeEvidence() { paperclipTaskCommunicationGuidance: context.paperclipTaskCommunicationGuidance, paperclipHarnessCheckedOut: context.paperclipHarnessCheckedOut, paperclipExternalChatExecutionBound: context.paperclipExternalChatExecutionBound, wake: { externalChatProvider: wake.externalChatProvider, checkedOutByHarness: wake.checkedOutByHarness, externalChatExecutionBound: wake.externalChatExecutionBound } } }; }); - await writeFile(resolve(home, "evidence.pending.json"), JSON.stringify({ appPid: process.pid, at: new Date().toISOString(), reports, incoming, sessions, replies, tools, deliveries, publications, runs: runEvidence, wakeups, comments, interactions, questionDeliveries }), { mode: 0o600 }); + await writeFile(resolve(home, "evidence.pending.json"), JSON.stringify({ appPid: process.pid, at: new Date().toISOString(), reports, incoming, sessions, replies, tools, deliveries, publications, runs: runEvidence, wakeups, comments, interactions, questionDeliveries, pushActions }), { mode: 0o600 }); await rename(resolve(home, "evidence.pending.json"), resolve(home, "evidence.json")); } finally { evidenceWriting = false; } } diff --git a/tests/speko-native/authenticated.spec.ts b/tests/speko-native/authenticated.spec.ts index 38fa3fefed4..2ab517e125d 100644 --- a/tests/speko-native/authenticated.spec.ts +++ b/tests/speko-native/authenticated.spec.ts @@ -8,7 +8,7 @@ test("E03/E14: real signed-in callers cannot substitute companies, private tasks const memberContext = await browser.newContext(), outsiderContext = await browser.newContext(), anonymousContext = await browser.newContext(); const request = async (api: APIRequestContext, method: "POST" | "PATCH", path: string, data: unknown) => { const response = await api.fetch(`${origin}/api${path}`, { method, headers: { Origin: origin }, data }); - expect(response.ok(), `${method} ${path}: ${response.status()}`).toBe(true); + expect(response.ok(), `${method} ${path}: ${response.status()} ${await response.text()}`).toBe(true); return response.json(); }; const signUp = (api: APIRequestContext, name: string) => request(api, "POST", "/auth/sign-up/email", { name, email: `${randomUUID()}@example.test`, password: randomBytes(24).toString("base64url") }); @@ -27,6 +27,7 @@ test("E03/E14: real signed-in callers cannot substitute companies, private tasks await invite(memberContext.request, company.id); await invite(outsiderContext.request, other.id); await request(page.request, "PATCH", `/companies/${company.id}`, { requireBoardApprovalForNewAgents: false }); const agent = await request(page.request, "POST", `/companies/${company.id}/agents`, { name: "Voice worker", role: "general", adapterType: "process", adapterConfig: { command: "fixture" }, runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: true } } }); + await expect.poll(async () => (await (await page.request.get(`${origin}/api/agents/${agent.id}`)).json()).status).toBe("idle"); const endpoint = await request(memberContext.request, "POST", `/companies/${company.id}/chat-endpoints`, { provider: "speko", assignedAgentId: agent.id }); const configured = await request(memberContext.request, "POST", `/chat-endpoints/${endpoint.id}/setup`, { action: "configure", credentials: { apiKey: "fixture-speko-key", agentId: "agent_member", signingSecret: `whsec_${randomBytes(32).toString("base64")}` } }); expect(configured.setup.step).toBe("test"); diff --git a/tests/speko-native/integrated.spec.ts b/tests/speko-native/integrated.spec.ts index 4c3d985be87..bed79718f91 100644 --- a/tests/speko-native/integrated.spec.ts +++ b/tests/speko-native/integrated.spec.ts @@ -244,6 +244,11 @@ test("E01/E03–E11/E13/E15/E16: setup, delayed work, duplicate input, navigatio expect(await providerCommand(phoneWork)).toEqual(incomingAccepted); const boundIncoming = (await evidence()).sessions.find((call: any) => call.providerSessionId === incoming.sessionId); await expect.poll(async () => (await evidence()).tools.filter((call: any) => call.sessionId === boundIncoming.id && call.tool === "submit_request").length).toBe(1); + // A saved task answer must reach the live phone transport before hangup. + // Provider acceptance is asserted separately from actual spoken playback. + await expect.poll(async () => (await evidence()).comments.some((row: any) => row.issueId === inboundTask.id && row.authorAgentId === agent.id && row.body.includes("Verification number")), {timeout: 100_000}).toBe(true); + await expect.poll(async () => (await providerCommand({action: "messages", sessionId: incoming.sessionId})).some((message: any) => message.text.includes("Verification number")), {timeout: 30_000}).toBe(true); + await expect.poll(async () => (await evidence()).pushActions.some((action: any) => action.payload.sessionId === boundIncoming.id && action.status === "completed" && action.result?.messageId && action.result.playback === "unknown")).toBe(true); await post(`/companies/${company.id}/voice-sessions/${boundIncoming.id}/end`, {}); // E15: report reconciliation persists one report, excludes recordings and keeps task assignment. await expect.poll(async () => (await evidence()).reports.find((report: any) => report.sessionId === boundIncoming.id)?.status, {timeout: 45000}).toBe("available"); diff --git a/tests/speko-native/live-browser.mjs b/tests/speko-native/live-browser.mjs index 8d347d273c1..8130f7710df 100644 --- a/tests/speko-native/live-browser.mjs +++ b/tests/speko-native/live-browser.mjs @@ -98,9 +98,12 @@ try { await page.getByRole('button', { name: `Talk to ${fixture.agentName}`, exact: true }).click(); } else if (process.env.SPEKO_NATIVE_CONNECTED === '1') { if (!fixture.endpointId) throw new Error('Connected qualification requires the verified endpoint fixture'); - await page.goto(`${origin}/${fixture.companyPrefix}/apps/chat/${fixture.endpointId}/settings`); - await expect(page.getByRole('button', {name: 'Start voice', exact: true}).or(page.getByRole('button', {name: 'Continue setup', exact: true}))).toBeVisible({timeout: 30000}); - if (await page.getByRole('button', {name: 'Continue setup', exact: true}).isVisible()) await page.getByRole('button', {name: 'Continue setup', exact: true}).click(); + const taskResponse = await page.request.post(`${origin}/api/companies/${fixture.companyId}/issues`, {headers: {Origin: origin}, data: {title: "Speko live browser qualification", assigneeAgentId: fixture.agentId, status: "backlog"}}); + if (!taskResponse.ok()) throw new Error(`Qualification task creation rejected (${taskResponse.status()})`); + const task = await taskResponse.json(); + await page.goto(`${origin}/${fixture.companyPrefix}/issues/${task.id}`); + await page.getByRole('button', {name: `Talk to ${fixture.agentName}`, exact: true}).click(); + event('qualification_task_created', {issueId: task.id}); event('existing_connection_used', {endpointId: fixture.endpointId}); } else { await page.getByRole('link', { name: 'Connectors', exact: true }).first().click(); diff --git a/tests/speko-native/stub-provider.ts b/tests/speko-native/stub-provider.ts index 5f0b2933770..202d0982a68 100644 --- a/tests/speko-native/stub-provider.ts +++ b/tests/speko-native/stub-provider.ts @@ -10,6 +10,7 @@ type Session = { id: string; agentId: string; token: string; endedAt: string | n export async function installSpekoTestProvider(origin: string, port: number) { const originalFetch = globalThis.fetch; const tools = new Map(), sessions = new Map(), hooks = new Map(); + const messages = new Map(); let numberAgentId: string | null = null; const creditRejectedAgents = new Set(), creationAttempts = new Map(); // The simulated external provider outlives an app restart, just as Speko does. @@ -20,10 +21,11 @@ export async function installSpekoTestProvider(origin: string, port: number) { for (const [key, value] of state.tools) tools.set(key, value); numberAgentId = state.numberAgentId ?? null; for (const [key, value] of state.hooks ?? []) hooks.set(key, value); + for (const [key, value] of state.messages ?? []) messages.set(key, value); for (const [key, value] of state.sessions) sessions.set(key, value); } const persist = () => { - writeFileSync(`${stateFile}.pending`, JSON.stringify({ tools: [...tools], sessions: [...sessions], hooks: [...hooks], numberAgentId }), { mode: 0o600 }); + writeFileSync(`${stateFile}.pending`, JSON.stringify({ tools: [...tools], sessions: [...sessions], hooks: [...hooks], messages: [...messages], numberAgentId }), { mode: 0o600 }); renameSync(`${stateFile}.pending`, stateFile); }; const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); @@ -60,6 +62,16 @@ export async function installSpekoTestProvider(origin: string, port: number) { if (url.pathname.endsWith("/phone")) return json({ sessionId: id, status: "dialing" }); return json({ sessionId: id, transportToken: `fixture:${id}`, transportUrl: "wss://speko-transport.invalid" }); } + const messageCall = /^\/v1\/calls\/([^/]+)\/messages$/.exec(url.pathname); + if (messageCall && method === "POST") { + const session = sessions.get(messageCall[1]); + if (!session) return json({error: "unknown fixture call"}, 404); + if (session.endedAt) return json({error: "call already ended"}, 409); + if (typeof body.text !== "string" || !body.text.trim() || body.mode !== "respond") return json({error: "invalid message"}, 400); + const message = {id: `message_${randomUUID()}`, sessionId: session.id, text: body.text, mode: body.mode}; + messages.set(session.id, [...messages.get(session.id) ?? [], message]); persist(); + return json({message_id: message.id}, 202); + } const call = /^\/v1\/calls\/([^/]+)(\/end)?$/.exec(url.pathname); if (call) { const session = sessions.get(call[1]); if (!session) return json({ error: "unknown fixture call" }, 404); @@ -95,6 +107,9 @@ export async function installSpekoTestProvider(origin: string, port: number) { sessions.set(id, {id, agentId: command.agentId, token: payload.toolSecrets.paperclip_session_token, endedAt: null, mode: "inbound_phone"}); persist(); res.writeHead(200, {"content-type": "application/json"}).end(JSON.stringify({sessionId: id, firstMessage: payload.firstMessage})); return; } + if (command.action === "messages") { + res.writeHead(200, {"content-type": "application/json"}).end(JSON.stringify(messages.get(command.sessionId) ?? [])); return; + } const session = sessions.get(command.sessionId); const tool = session && tools.get(session.agentId)?.find(item => item.name === command.tool); if (!session || session.endedAt || !tool) { res.writeHead(404).end(); return; } diff --git a/tests/speko-voice-proof/browser-client.mjs b/tests/speko-voice-proof/browser-client.mjs index eb5f4412b32..87600f61ebe 100644 --- a/tests/speko-voice-proof/browser-client.mjs +++ b/tests/speko-voice-proof/browser-client.mjs @@ -133,6 +133,6 @@ $('mute').onclick = async () => { try { await conversation.setMicMuted(!muted); muted = !muted; $('mute').textContent = muted ? 'Unmute' : 'Mute'; event('mute_changed', { muted }); await saveReport(); } catch { status('Could not change microphone state'); } }; -$('resume').onclick = async () => { await conversation.startAudioPlayback(); $('resume').hidden = !conversation.canPlaybackAudio; }; +$('resume').onclick = async () => { await conversation.startAudioPlayback(); $('resume').hidden = conversation.canPlaybackAudio; }; $('end').onclick = () => end().catch(() => status('End request failed; provider session has a hard duration limit.')); window.addEventListener('pagehide', () => { void conversation?.endSession(); }); diff --git a/tests/speko-voice-proof/live-client.mjs b/tests/speko-voice-proof/live-client.mjs index c710a255331..794ceda4a8e 100644 --- a/tests/speko-voice-proof/live-client.mjs +++ b/tests/speko-voice-proof/live-client.mjs @@ -221,26 +221,35 @@ try { event("script_failed", { reason: failure }); } finally { stopping = true; + const cleanupFailures = []; + const cleanup = async (operation, close) => { + try { await close(); } catch (error) { cleanupFailures.push({operation, reason: error.message}); event("cleanup_failed", {operation}); } + }; await Promise.allSettled(audioReaders.map((reader) => reader.cancel())); - proof.close(); - server.close(); - server.closeAllConnections(); + await cleanup("proof.close", () => proof.close()); + await cleanup("server.close", () => { server.close(); server.closeAllConnections(); }); if (sessionId) { try { const ended = await api(`/v1/calls/${encodeURIComponent(sessionId)}/end`, {}); event("session_end_requested", { status: ended.status }); } catch { event("session_end_failed"); } } - await room.disconnect(); - if (notifierRoom) await notifierRoom.disconnect(); - await source.close(); - await Promise.allSettled([pump, ...consumers]); - await dispose(); + for (const [name, close] of [ + ["room.disconnect", () => room.disconnect()], + ["notifier.disconnect", () => notifierRoom?.disconnect()], + ["source.close", () => source.close()], + ["consumers", () => Promise.allSettled([pump, ...consumers])], + ["dispose", () => dispose()], + ]) { + await cleanup(name, close); + } process.removeListener("SIGINT", interrupt); process.removeListener("SIGTERM", interrupt); // These files contain only this synthetic client/session, never human audio. - await writeFile(resolve(out, "output.pcm"), Buffer.concat(audioFrames.map((f) => f.data)), { mode: 0o600 }); - if (resultAt !== undefined) await writeFile(resolve(out, "result.pcm"), Buffer.concat(audioFrames.filter((f) => f.at >= resultAt - 250).map((f) => f.data)), { mode: 0o600 }); - const report = { startedAt, sourceDigests, sessionId, mode, provider, notifyReady, notifyViaJoin, interruptAcknowledgment, failure: failure ?? null, firstAudio, resultAt, resultAudioAt, lastAudio, audioBursts, audioFrames: audioFrames.length, proof: proof.evidence(), events, syntheticTranscript: transcript, qualification: "requires_audio_and_transport_review" }; + try { + await writeFile(resolve(out, "output.pcm"), Buffer.concat(audioFrames.map((f) => f.data)), {mode: 0o600}); + if (resultAt !== undefined) await writeFile(resolve(out, "result.pcm"), Buffer.concat(audioFrames.filter((f) => f.at >= resultAt - 250).map((f) => f.data)), {mode: 0o600}); + } catch (error) { cleanupFailures.push({operation: "audio_evidence", reason: error.message}); } + const report = { cleanupFailures, startedAt, sourceDigests, sessionId, mode, provider, notifyReady, notifyViaJoin, interruptAcknowledgment, failure: failure ?? null, firstAudio, resultAt, resultAudioAt, lastAudio, audioBursts, audioFrames: audioFrames.length, proof: proof.evidence(), events, syntheticTranscript: transcript, qualification: "requires_audio_and_transport_review" }; await writeFile(resolve(out, "report.json"), JSON.stringify(report, null, 2), { mode: 0o600 }); console.log(JSON.stringify({ reportPath: resolve(out, "report.json"), resultReturned: report.proof.resultReturned, acceptedRequests: report.proof.acceptedRequests, failure: report.failure })); - process.exitCode = failure ? 1 : 0; + process.exitCode = failure || cleanupFailures.length ? 1 : 0; }