mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
fix(voice): preserve readable call history after secondary failures
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
b5e3f84eba
commit
dadb0f106b
5 files changed
+66
-9
No files matched your search
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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 }) {
|
||||
|
||||
@@ -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();
|
||||
} };
|
||||
Reference in new issue
Block a user