Merge branch 'codex/speko-voice-ui' into codex/speko-voice-qualification

* codex/speko-voice-ui:
  fix(voice): preserve readable call history after secondary failures
  test(voice): retrieve phone questions with the current call credential
This commit is contained in:
Dotta committed 2026-10-09 15:43:29 -05:00
commit 542c90f9ba
6 files changed
+73 -11

No files matched your search

@@ -457,7 +457,7 @@ const support = await getEmbeddedPostgresTestSupport();
configureVoiceDefaults: vi.fn(async () => {}),
verifyAgent: vi.fn(async () => ({ id: "agent_test", organizationId: "org_test", name: "Test voice" })),
createPhoneSession: vi.fn(async (_input: { to: string; bindingId: string }) => ({ sessionId: randomUUID(), status: "dialing" as const })),
createBrowserSession: vi.fn(async () => ({ sessionId: randomUUID(), transportToken: "short-lived-media-token", transportUrl: "wss://media.example.test" })),
createBrowserSession: vi.fn(async (_input: {toolToken: string}) => ({ sessionId: randomUUID(), transportToken: "short-lived-media-token", transportUrl: "wss://media.example.test" })),
inspectSession: vi.fn(async () => ({ status: "active", endedAt: null as string | null })),
callReport: vi.fn(async () => ({ complete: true, transcript: [{ id: "turn1", index: 0, speaker: "caller" as const, text: "A test request", startedAt: new Date().toISOString(), endedAt: null, interrupted: false }], costMicroUsd: "120000", durationSeconds: 60, providerUpdatedAt: new Date() })),
callDeliveryDiagnostics: vi.fn(async (id: string, deliveries: readonly {messageId: string; acceptedAt: string}[]) => parseSpekoDeliveryDiagnostics(
@@ -492,7 +492,12 @@ const support = await getEmbeddedPostgresTestSupport();
expect(f.transport.sendCallMessage.mock.calls[0]?.[1]).toContain("Call get_updates");
const [reply] = await db.select().from(chatVoiceReplies).where(eq(chatVoiceReplies.publicationId, f.publication.id));
expect(reply.deliveredAt).toBeNull();
expect(await f.store.runTool(f.toolInput("get_updates", {cursor: 0}))).toMatchObject({updates: [{question: {interactionId}}]});
// The service starts a new call; the first fixture call's token is retired.
const token = f.transport.createBrowserSession.mock.calls[0]![0].toolToken;
const toolId = randomUUID();
const {sessionId: providerSessionId} = await f.transport.createBrowserSession.mock.results[0]!.value;
const envelope = {session_id: providerSessionId, tool_call_id: toolId, idempotency_key: `${providerSessionId}:${toolId}`, tool: "get_updates" as const, args: {cursor: 0}};
expect(await f.store.runTool({...f.toolInput("get_updates", {cursor: 0}), sessionId: f.session.id, token, envelope, webhookId: toolId, fingerprint: createHash("sha256").update(JSON.stringify(envelope)).digest("hex")})).toMatchObject({updates: [{question: {interactionId}}]});
await f.push();
expect(f.transport.sendCallMessage).toHaveBeenCalledTimes(2);
});
@@ -0,0 +1,41 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { MemoryRouter } from "react-router-dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SpekoCallHistory } from "./SpekoCallHistory";
import { callHistoryFixture } from "../../../storybook/fixtures/spekoCallHistory";
const mocks = vi.hoisted(() => ({list: vi.fn(), incoming: vi.fn(), end: vi.fn()}));
vi.mock("@/api/voiceHistory", () => ({voiceHistoryApi: {list: mocks.list}}));
vi.mock("@/api/voicePhone", () => ({voicePhoneApi: {history: mocks.incoming}}));
vi.mock("@/api/voiceSessions", () => ({voiceSessionsApi: {end: mocks.end}}));
describe("saved Speko call history", () => {
let container: HTMLDivElement, root: Root, query: QueryClient;
beforeEach(() => {
vi.clearAllMocks(); container = document.createElement("div"); document.body.append(container);
root = createRoot(container); query = new QueryClient({defaultOptions: {queries: {retry: false}, mutations: {retry: false}}});
mocks.list.mockResolvedValue([callHistoryFixture]); mocks.incoming.mockResolvedValue([]);
});
afterEach(async () => {await act(async () => root.unmount()); query.clear(); container.remove();});
async function render() {
await act(async () => root.render(<MemoryRouter><QueryClientProvider client={query}><SpekoCallHistory companyId="company" endpointId="endpoint" /></QueryClientProvider></MemoryRouter>));
}
it("keeps completed call transcripts when paused inbound admission cannot load", async () => {
mocks.incoming.mockRejectedValue(new Error("Connection is paused")); await render();
await vi.waitFor(() => expect(container.textContent).toContain("Unapproved calls could not be loaded"));
expect(container.querySelector("summary")?.textContent).toContain("Completed");
expect(container.querySelector('[aria-label="Call transcript"]')).not.toBeNull();
});
it("keeps readable call history after a failed end-call request", async () => {
mocks.list.mockResolvedValue([{...callHistoryFixture, session: {...callHistoryFixture.session, state: "active", endedAt: null}}]);
mocks.end.mockRejectedValue(new Error("Provider unavailable")); await render();
await vi.waitFor(() => expect(container.querySelector("summary")).not.toBeNull());
const end = [...container.querySelectorAll("button")].find(button => button.textContent === "End call")!;
await act(async () => end.click());
await vi.waitFor(() => expect(container.textContent).toContain("The call could not be ended"));
expect(container.querySelector("summary")?.textContent).toContain("In progress");
expect(container.querySelector('[aria-label="Call transcript"]')).not.toBeNull();
});
});
+7 -5
View File
@@ -41,22 +41,24 @@ export function SpekoCallActivityItem({ entry: { session, report }, onEnd, endin
export function SpekoUnapprovedCallActivityItem({ call, presentation = "history" }: { call: VoiceUnapprovedCallHistoryEntry; presentation?: "history" | "activity" }) {
return <div data-activity-kind="unapproved_call" className={presentation === "activity" ? "px-2 py-3 text-sm" : "rounded-md border border-border p-3 text-sm"}><p>{call.state === "denied" ? "Call denied" : call.state === "expired" ? "Approval expired" : "Missed call"} · {new Date(call.createdAt).toLocaleString()}</p><p className="text-xs text-muted-foreground">No private task was connected.</p></div>;
}
export interface SpekoCallHistoryViewProps { entries?: VoiceCallHistoryEntry[]; unapprovedCalls?: VoiceUnapprovedCallHistoryEntry[]; loading?: boolean; error?: string; onRetry(): void; onEnd?(sessionId: string): void; endingSessionId?: string }
export function SpekoCallHistoryView({ entries = [], unapprovedCalls = [], loading, error, onRetry, onEnd, endingSessionId }: SpekoCallHistoryViewProps) {
export interface SpekoCallHistoryViewProps { entries?: VoiceCallHistoryEntry[]; unapprovedCalls?: VoiceUnapprovedCallHistoryEntry[]; loading?: boolean; error?: string; incomingError?: string; endError?: string; onRetry(): void; onEnd?(sessionId: string): void; endingSessionId?: string }
export function SpekoCallHistoryView({ entries = [], unapprovedCalls = [], loading, error, incomingError, endError, onRetry, onEnd, endingSessionId }: SpekoCallHistoryViewProps) {
return <section className="max-w-xl space-y-3" aria-label="Your calls">
<div className="flex items-center justify-between gap-3"><h2 className="text-lg font-semibold">Your calls</h2><Button size="sm" variant="ghost" onClick={onRetry} disabled={loading}>Refresh</Button></div>
{loading && <p role="status" className="text-sm text-muted-foreground">Loading calls…</p>}
{error && <div className="space-y-2"><p role="alert" className="text-sm text-destructive">{error}</p><Button size="sm" variant="outline" onClick={onRetry}>Try again</Button></div>}
{!loading && !error && !entries.length && !unapprovedCalls.length && <p className="text-sm text-muted-foreground">Your browser conversations and phone calls will appear here.</p>}
{incomingError && <p role="alert" className="text-sm text-destructive">Unapproved calls could not be loaded. {incomingError}</p>}
{endError && <p role="alert" className="text-sm text-destructive">The call could not be ended. {endError}</p>}
{!loading && !error && !incomingError && !entries.length && !unapprovedCalls.length && <p className="text-sm text-muted-foreground">Your browser conversations and phone calls will appear here.</p>}
{!error && entries.map(entry => <SpekoCallActivityItem key={entry.session.id} entry={entry} onEnd={onEnd} ending={endingSessionId === entry.session.id} />)}
{!error && unapprovedCalls.length > 0 && <div className="space-y-2"><h3 className="text-sm font-medium">Unapproved incoming calls</h3><ul className="space-y-2">{unapprovedCalls.map(call => <li key={call.id}><SpekoUnapprovedCallActivityItem call={call} /></li>)}</ul></div>}
{!incomingError && unapprovedCalls.length > 0 && <div className="space-y-2"><h3 className="text-sm font-medium">Unapproved incoming calls</h3><ul className="space-y-2">{unapprovedCalls.map(call => <li key={call.id}><SpekoUnapprovedCallActivityItem call={call} /></li>)}</ul></div>}
</section>;
}
export function useSpekoCallHistory(companyId: string, endpointId: string, enabled = true) {
const query = useQuery({ queryKey: ["speko-history", companyId, endpointId], queryFn: () => voiceHistoryApi.list(companyId, endpointId), enabled, retry: false, refetchInterval: enabled ? 30_000 : false });
const incoming = useQuery({queryKey: ["speko-unapproved-history", companyId, endpointId], queryFn: () => voicePhoneApi.history(companyId, endpointId), retry: false, enabled: enabled && query.isSuccess, refetchInterval: enabled ? 30_000 : false});
const ending = useMutation({mutationFn: (sessionId: string) => voiceSessionsApi.end(companyId, sessionId), onSuccess: () => query.refetch()});
return { entries: query.data ?? [], unapprovedCalls: incoming.data ?? [], loading: query.isLoading || incoming.isLoading, error: (ending.error ?? query.error ?? incoming.error)?.message, endingSessionId: ending.isPending ? ending.variables : undefined,
return { entries: query.data ?? [], unapprovedCalls: incoming.data ?? [], loading: query.isLoading || incoming.isLoading, error: query.error?.message, incomingError: incoming.error?.message, endError: ending.error?.message, endingSessionId: ending.isPending ? ending.variables : undefined,
onEnd: (sessionId: string) => ending.mutate(sessionId), onRetry: () => { ending.reset(); void query.refetch(); void incoming.refetch(); } };
}
export function SpekoCallHistory({ companyId, endpointId }: { companyId: string; endpointId: string }) {
+2 -1
View File
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from "vitest";
import type { voiceSessionsApi } from "@/api/voiceSessions";
import type { VoiceSession, VoiceSessionMedia } from "@paperclipai/shared";
import { createVoiceCallAttempt, voiceCallJournal } from "./voice-call-attempt";
import { ApiError } from "@/api/client";
@@ -9,7 +10,7 @@ function fixture() {
const storage = { getItem: (key: string) => rows.get(key) ?? null, setItem: (key: string, value: string) => { rows.set(key, value); }, removeItem: (key: string) => { rows.delete(key); } };
const session = { id: "session", state: "active" } as VoiceSession;
const media = { sessionId: "session", generation: 1, transportToken: "must-never-be-saved", transportUrl: "wss://test.invalid" } satisfies VoiceSessionMedia;
const client = { start: vi.fn(async () => ({ session, media })), end: vi.fn(async () => ({ ...session, state: "ended" as const })), get: vi.fn(async () => session), notification: vi.fn(async () => null) };
const client = { start: vi.fn(async (..._args: Parameters<typeof voiceSessionsApi.start>) => ({ session, media })), end: vi.fn(async () => ({ ...session, state: "ended" as const })), get: vi.fn(async () => session), notification: vi.fn(async () => null) };
const journal = voiceCallJournal(storage, "company", "operator");
return { rows, storage, client, journal };
}
@@ -1005,7 +1005,7 @@ function Activity({
const activityEntries = [
...(!query.isError ? rows.map(item => ({ kind: "connection" as const, id: `connection:${item.id}`, createdAt: item.createdAt, item })) : []),
...(!cursor && !calls.error ? calls.entries.map(entry => ({ kind: "call" as const, id: `call:${entry.session.id}`, createdAt: entry.session.createdAt, entry })) : []),
...(!cursor && !calls.error ? calls.unapprovedCalls.map(call => ({ kind: "unapproved_call" as const, id: `unapproved:${call.id}`, createdAt: call.createdAt, call })) : []),
...(!cursor && !calls.incomingError ? calls.unapprovedCalls.map(call => ({ kind: "unapproved_call" as const, id: `unapproved:${call.id}`, createdAt: call.createdAt, call })) : []),
].sort((a, b) => b.createdAt.localeCompare(a.createdAt) || a.id.localeCompare(b.id));
const { status } = endpoint;
@@ -1201,7 +1201,11 @@ function Activity({
</Button>
</div>
)}
{calls.error && endpoint.provider === "speko" && !cursor && <div className="flex flex-wrap items-center justify-between gap-3 py-4"><p role="alert" className="text-sm text-destructive">Call activity could not be loaded. {calls.error}</p><Button size="sm" variant="outline" onClick={calls.onRetry}>Retry calls</Button></div>}
{endpoint.provider === "speko" && !cursor && [
calls.error && `Call activity could not be loaded. ${calls.error}`,
calls.incomingError && `Unapproved calls could not be loaded. ${calls.incomingError}`,
calls.endError && `The call could not be ended. ${calls.endError}`,
].filter(Boolean).map((message) => <div key={String(message)} className="flex flex-wrap items-center justify-between gap-3 py-4"><p role="alert" className="text-sm text-destructive">{message}</p><Button size="sm" variant="outline" onClick={calls.onRetry}>Retry calls</Button></div>)}
{activityEntries.map(entry => {
if (entry.kind === "call") return <SpekoCallActivityItem key={entry.id} entry={entry.entry} presentation="activity" onEnd={calls.onEnd} ending={calls.endingSessionId === entry.entry.session.id} />;
if (entry.kind === "unapproved_call") return <SpekoUnapprovedCallActivityItem key={entry.id} call={entry.call} presentation="activity" />;
@@ -1267,7 +1271,7 @@ function Activity({
</div>
);
})}
{!query.isLoading && !query.isError && !calls.loading && !calls.error && activityEntries.length === 0 && (
{!query.isLoading && !query.isError && !calls.loading && !calls.error && !calls.incomingError && activityEntries.length === 0 && (
<p className="py-5 text-sm text-muted-foreground">
No connection activity yet.
</p>
@@ -35,3 +35,12 @@ export const ActivityEndCallFocus: Story = { render: function ActivityFocusFixtu
const [ended, setEnded] = useState(false);
return <SpekoCallActivityItem presentation="activity" onEnd={() => setEnded(true)} entry={{...entry, session: {...entry.session, state: ended ? "ended" : "active", endedAt: ended ? entry.session.endedAt : null}}} />;
}, play: EndCallFocus.play };
export const IncomingFailurePreservesHistory: Story = { args: { entries: [entry], incomingError: "This connection is paused." }, play: async ({canvasElement}) => {
const c = within(canvasElement); await expect(c.getByRole("alert")).toHaveTextContent("Unapproved calls could not be loaded");
await userEvent.click(canvasElement.querySelector("summary")!); await expect(c.getByRole("list", {name: "Call transcript"})).toBeVisible();
} };
export const EndFailurePreservesHistory: Story = { args: { entries: [entry], endError: "Try again after reconnecting." }, play: async ({canvasElement}) => {
const c = within(canvasElement); await expect(c.getByRole("alert")).toHaveTextContent("The call could not be ended");
await userEvent.click(canvasElement.querySelector("summary")!); await expect(c.getByRole("link", {name: "Conversation task"})).toBeVisible();
} };