mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
test(voice): qualify phone reply pushes and preserve live probe evidence
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
1523c23a05
commit
18f9383a85
7 files changed
+55
-21
No files matched your search
@@ -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<string, unknown>;
|
||||
@@ -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; }
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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");
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<string, Tool[]>(), sessions = new Map<string, Session>(), hooks = new Map<string, any>();
|
||||
const messages = new Map<string, {id: string; sessionId: string; text: string; mode: string}[]>();
|
||||
let numberAgentId: string | null = null;
|
||||
const creditRejectedAgents = new Set<string>(), creationAttempts = new Map<string, number>();
|
||||
// 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; }
|
||||
|
||||
@@ -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(); });
|
||||
@@ -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;
|
||||
}
|
||||
Reference in new issue
Block a user