fix: finish Speko request recovery and setup footer

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-09 16:32:15 -05:00
1 parent eb6fa7c4f9
commit fe774f98fd
9 files changed
+97 -16

No files matched your search

@@ -0,0 +1,37 @@
// @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 {SpekoIncomingCalls} from "./SpekoIncomingCalls";
const mocks = vi.hoisted(() => ({incoming: vi.fn(), list: vi.fn()}));
vi.mock("@/api/voicePhone", () => ({voicePhoneApi: {incoming: mocks.incoming}}));
vi.mock("@/api/issues", () => ({issuesApi: {list: mocks.list}}));
describe("incoming call task selection", () => {
let container: HTMLDivElement, root: Root, client: QueryClient;
const tasks = [{id: "task", status: "todo", identifier: "PAP-42", title: "Ready task"}];
beforeEach(() => {
vi.resetAllMocks(); container = document.createElement("div"); document.body.append(container);
root = createRoot(container); client = new QueryClient({defaultOptions: {queries: {retry: false}}});
mocks.incoming.mockResolvedValue([{id: "call", state: "awaiting_approval", approvalCode: "123456"}]);
});
afterEach(async () => {await act(async () => root.unmount()); client.clear(); container.remove();});
async function render() {await act(async () => root.render(<MemoryRouter><QueryClientProvider client={client}><SpekoIncomingCalls companyId="company" endpointId="endpoint" agentId="agent" /></QueryClientProvider></MemoryRouter>));}
it("shows task request failures and lets callers retry the existing task inventory", async () => {
mocks.list.mockRejectedValueOnce(new Error("Offline")).mockResolvedValue(tasks); await render();
await vi.waitFor(() => expect(container.textContent).toContain("Task list could not be loaded"));
const retry = [...container.querySelectorAll("button")].find(button => button.textContent === "Retry tasks")!;
await act(async () => retry.click());
await vi.waitFor(() => expect(container.querySelector('option[value="task"]')).not.toBeNull());
expect(container.querySelector('[role="alert"]')).toBeNull();
});
it("preserves previously loaded tasks when a background task request fails", async () => {
mocks.list.mockResolvedValue(tasks); await render();
await vi.waitFor(() => expect(container.querySelector('option[value="task"]')).not.toBeNull());
mocks.list.mockRejectedValue(new Error("Offline"));
await act(async () => {await client.refetchQueries({queryKey: ["speko-approval-tasks", "company", "agent"]});});
await vi.waitFor(() => expect(container.textContent).toContain("Task list could not be loaded"));
expect(container.querySelector('option[value="task"]')).not.toBeNull();
});
});
@@ -36,7 +36,8 @@ export function SpekoIncomingCalls({companyId, endpointId, agentId}: {companyId:
const [decision, setDecision] = useState<VoiceInboundCall>();
useEffect(() => { setDecision(undefined); }, [companyId, endpointId]);
const query = useQuery({queryKey: ["speko-incoming", companyId, endpointId], queryFn: () => voicePhoneApi.incoming(companyId, endpointId), refetchInterval: 2000, retry: false});
const tasks = useQuery({queryKey: ["speko-approval-tasks", companyId, agentId], queryFn: () => issuesApi.list(companyId, {assigneeAgentId: agentId}), enabled: Boolean(query.data?.length), retry: false});
const needsTaskSelection = Boolean(query.data?.some(call => ["awaiting_approval", "approving"].includes(call.state)));
const tasks = useQuery({queryKey: ["speko-approval-tasks", companyId, agentId], queryFn: () => issuesApi.list(companyId, {assigneeAgentId: agentId}), enabled: needsTaskSelection, retry: false});
const mutation = useMutation({mutationFn: ({id, ...input}: {id: string; approve: boolean; approvalCode: string; issueId?: string}) => voicePhoneApi.decide(companyId, endpointId, id, input), onSuccess: result => { setDecision(result); return query.refetch(); }});
return <div className="space-y-3">{query.error && <p role="alert" className="text-sm text-destructive">Incoming call approval is unavailable. {query.error.message}</p>}{!query.error && [...(query.data ?? []).filter(call => call.id !== decision?.id), ...(decision ? [decision] : [])].map(call => <SpekoIncomingCallCard key={call.id} call={call} tasks={tasks.error ? [] : tasks.data?.filter(task => !["done", "cancelled"].includes(task.status)).map(task => ({id: task.id, label: `${task.identifier ?? "Task"} · ${task.title}`}))} busy={mutation.isPending && mutation.variables?.id === call.id} error={mutation.variables?.id === call.id ? mutation.error?.message : undefined} onDecide={input => mutation.mutate({id: call.id, ...input})} />)}</div>;
return <div className="space-y-3">{needsTaskSelection && tasks.isError && <div role="alert" className="space-y-2 text-sm"><p>Task list could not be loaded. Retry to choose an existing task.</p><Button variant="outline" disabled={tasks.isFetching} onClick={() => void tasks.refetch()}>Retry tasks</Button></div>}{query.error && <p role="alert" className="text-sm text-destructive">Incoming call approval is unavailable. {query.error.message}</p>}{!query.error && [...(query.data ?? []).filter(call => call.id !== decision?.id), ...(decision ? [decision] : [])].map(call => <SpekoIncomingCallCard key={call.id} call={call} tasks={tasks.data?.filter(task => !["done", "cancelled"].includes(task.status)).map(task => ({id: task.id, label: `${task.identifier ?? "Task"} · ${task.title}`}))} busy={mutation.isPending && mutation.variables?.id === call.id} error={mutation.variables?.id === call.id ? mutation.error?.message : undefined} onDecide={input => mutation.mutate({id: call.id, ...input})} />)}</div>;
}
@@ -1,8 +1,10 @@
import { Button } from "@/components/ui/button";
import { SetupWizardFooter } from "@/components/SetupWizard";
import { Input } from "@/components/ui/input";
export interface SpekoProviderSetupProps {
agentName: string;
onSaveExit?(): void;
credentials: Record<string, string>;
onChange(values: Record<string, string>): void;
onConnect(values: Record<string, string>): void;
@@ -10,7 +12,7 @@ export interface SpekoProviderSetupProps {
pending?: boolean;
repairing?: boolean;
}
export function SpekoProviderSetup({ agentName, credentials, onChange, onConnect, callbackUrl, pending = false, repairing = false }: SpekoProviderSetupProps) {
export function SpekoProviderSetup({ agentName, onSaveExit, credentials, onChange, onConnect, callbackUrl, pending = false, repairing = false }: SpekoProviderSetupProps) {
const ready = repairing || Boolean(credentials.apiKey?.trim() && credentials.agentId?.trim());
const reachable = callbackUrl?.startsWith("https://") === true;
function connect() {
@@ -39,6 +41,6 @@ export function SpekoProviderSetup({ agentName, credentials, onChange, onConnect
{!reachable && <p role="alert" className="text-sm text-destructive">Configure a public HTTPS callback origin for Paperclip first. Local instances need an explicitly configured tunnel or reverse proxy.</p>}
{reachable && <p className="break-all text-xs text-muted-foreground">Callback: {callbackUrl}</p>}
<p className="text-sm text-muted-foreground">Credentials and a generated callback signing secret are saved in the company vault. Speko charges for voice usage separately from agent work. Outgoing calls are experimental. After connecting, save your callback number to let this agent call you about your tasks.</p>
<Button disabled={!ready || !reachable || pending} onClick={connect}>{pending ? "Verifying Speko…" : repairing ? "Reconnect Speko" : "Connect Speko"}</Button>
{onSaveExit ? <SetupWizardFooter onSaveExit={onSaveExit} disabled={pending}><Button disabled={!ready || !reachable || pending} onClick={connect}>{pending ? "Verifying Speko…" : repairing ? "Reconnect Speko" : "Connect Speko"}</Button></SetupWizardFooter> : <div className="flex justify-end"><Button disabled={!ready || !reachable || pending} onClick={connect}>{pending ? "Verifying Speko…" : repairing ? "Reconnect Speko" : "Connect Speko"}</Button></div>}
</div>;
}
@@ -24,9 +24,11 @@ describe("task voice connection failures", () => {
mocks.list.mockRejectedValueOnce(new Error("Offline")).mockResolvedValue([spekoEndpoint]); await render(bound);
await vi.waitFor(() => expect(container.querySelector('[role="alert"]')?.textContent).toContain("Voice connections could not be loaded"));
expect(container.textContent).not.toContain("Voice is unavailable");
container.querySelector('button')!.focus();
await act(async () => container.querySelector('button')!.click());
await vi.waitFor(() => expect(container.textContent).toContain(`Talk to ${spekoEndpoint.assignedAgentName}`));
expect(container.querySelector('[role="alert"]')).toBeNull();
expect(document.activeElement).toBe(container.querySelector('button'));
});
it("keeps active controls mounted when a background connection refresh fails", async () => {
mocks.list.mockResolvedValue([spekoEndpoint]); await render();
@@ -1,4 +1,4 @@
import { useRef, useState } from "react";
import { useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { chatEndpointsApi } from "@/api/chatEndpoints";
import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled";
@@ -6,16 +6,21 @@ import { Button } from "@/components/ui/button";
import { NativeVoiceConversation } from "./NativeVoiceConversation";
export function TaskVoiceLauncher({ companyId, issueId, agentId, boundEndpointId }: { companyId: string; issueId: string; agentId?: string | null; boundEndpointId?: string }) {
const launcher = useRef<HTMLButtonElement>(null);
const launcher = useRef<HTMLButtonElement>(null), restoreFocus = useRef(false);
const { enabled } = useChatConnectorsEnabled();
const [open, setOpen] = useState(false), [selected, setSelected] = useState("");
const connections = useQuery({ queryKey: ["task-voice-endpoints", companyId], queryFn: () => chatEndpointsApi.list(companyId), enabled: enabled && Boolean(agentId || boundEndpointId) });
useEffect(() => {
if (restoreFocus.current && !connections.isFetching && !connections.isError && launcher.current) {
restoreFocus.current = false; launcher.current.focus();
}
}, [connections.data, connections.isFetching, connections.isError]);
if (!enabled) return null;
const candidates = (connections.data ?? []).filter((endpoint) => endpoint.provider === "speko" && endpoint.status === "active" && (boundEndpointId ? endpoint.id === boundEndpointId : endpoint.assignedAgentId === agentId));
const endpoint = candidates.find((entry) => entry.id === selected) ?? candidates[0];
const connectionError = connections.isError ? <div role="alert" className="space-y-2 text-sm">
<p>Voice connections could not be loaded.</p>
<Button variant="outline" disabled={connections.isFetching} onClick={() => { void connections.refetch().then(result => { if (!result.isError) requestAnimationFrame(() => launcher.current?.focus()); }); }}>Retry voice connections</Button>
<Button variant="outline" disabled={connections.isFetching} onClick={() => { restoreFocus.current = true; void connections.refetch().then(result => { if (result.isError) restoreFocus.current = false; }); }}>Retry voice connections</Button>
</div> : null;
if (!endpoint && connectionError) return <section aria-label="Task voice conversation" className="space-y-3 rounded-lg border border-border p-4">{connectionError}</section>;
if (!endpoint) return boundEndpointId ? <p className="text-sm text-muted-foreground">{connections.isPending ? "Loading voice connection…" : "Voice is unavailable. Check the Speko connection in Apps."}</p> : null;
+2 -2
View File
@@ -670,7 +670,7 @@ function ChatSdkEndpointSetup() {
onSaveExit={() => navigate("/apps")}
/>
)}
{step !== 0 && !isSlack && !(provider === "speko" && step === tryStep) && <div className="flex justify-start">
{step !== 0 && !isSlack && provider !== "speko" && <div className="flex justify-start">
<Button className="text-muted-foreground" variant="ghost" onClick={() => navigate("/apps")}>
Save &amp; exit
</Button>
@@ -898,7 +898,7 @@ function ProviderConnectStep({
null,
2,
);
if (provider === "speko") return <SpekoProviderSetup agentName={agentName} credentials={credentials} onChange={setCredentials} onConnect={(values) => onAction(repairing ? "reconnect" : "configure", values)} callbackUrl={endpoint.setup?.webhookUrl} pending={pending} repairing={repairing} />;
if (provider === "speko") return <SpekoProviderSetup onSaveExit={() => navigate("/apps")} agentName={agentName} credentials={credentials} onChange={setCredentials} onConnect={(values) => onAction(repairing ? "reconnect" : "configure", values)} callbackUrl={endpoint.setup?.webhookUrl} pending={pending} repairing={repairing} />;
if (provider === "imessage-photon") return <PhotonConnectStep endpoint={endpoint} agentName={agentName} repairing={repairing} pending={pending} onAction={onAction} />;
if (provider === "discord") {
const applicationId = credentials.applicationId?.trim() ?? "";
@@ -6,7 +6,7 @@ import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
function Fixture(props: Partial<SpekoProviderSetupProps>) {
const [credentials, setCredentials] = useState(props.credentials ?? {});
const [connected, setConnected] = useState(false);
return connected ? <p role="status">Credentials saved. Continue to the test conversation.</p> : <SpekoProviderSetup agentName="Company Phone Agent" callbackUrl="https://paperclip.example/api/voice-webhooks/endpoint/tools" {...props} credentials={credentials} onChange={setCredentials} onConnect={(values) => { if (!props.repairing && !values.signingSecret?.startsWith("whsec_")) throw new Error("Missing signing secret"); setConnected(true); }} />;
return connected ? <p role="status">Credentials saved. Continue to the test conversation.</p> : <SpekoProviderSetup onSaveExit={() => {}} agentName="Company Phone Agent" callbackUrl="https://paperclip.example/api/voice-webhooks/endpoint/tools" {...props} credentials={credentials} onChange={setCredentials} onConnect={(values) => { if (!props.repairing && !values.signingSecret?.startsWith("whsec_")) throw new Error("Missing signing secret"); setConnected(true); }} />;
}
const meta: Meta<typeof SpekoProviderSetup> = { ...voiceStoryLifecycle, title: "Connections/Speko/Provider setup", component: SpekoProviderSetup, parameters: { layout: "padded" } };
export default meta;
@@ -30,6 +30,8 @@ export const KeyboardValidationAndConnect: Story = {
await expect(key).toHaveAttribute("type", "password");
await userEvent.type(key, "synthetic-not-a-key");
await userEvent.tab();
await expect(canvas.getByRole("button", { name: "Save & exit" })).toHaveFocus();
await userEvent.tab();
await expect(canvas.getByRole("button", { name: "Connect Speko" })).toHaveFocus();
await userEvent.keyboard("{Enter}");
await expect(canvas.getByRole("status")).toHaveTextContent("Credentials saved");
@@ -1,5 +1,5 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, userEvent, within } from "storybook/test";
import { expect, userEvent, waitFor, within } from "storybook/test";
import { TaskVoiceLauncher } from "@/components/voice/TaskVoiceLauncher";
import { AgentChannelsPanel } from "@/components/chat/AgentChannelsPanel";
import { ExternallyConnectedTaskBanner } from "@/components/chat/ExternallyConnectedTaskBanner";
@@ -44,6 +44,7 @@ function TaskConnectionFailure({ bound = false }: { bound?: boolean }) {
chatEndpointsApi.list = async () => [spekoEndpoint];
const queryKey = ["task-voice-endpoints", spekoCompanyId];
client.removeQueries({ queryKey });
client.setQueryDefaults(queryKey, { retryOnMount: false });
client.getQueryCache().build(client, { queryKey }).setState({ status: "error", error: new Error("Fixture connection failure"), fetchStatus: "idle" });
setReady(true);
return () => { chatEndpointsApi.list = original; client.removeQueries({ queryKey }); };
@@ -55,11 +56,11 @@ export const BoundConnectionRecovery: Story = {
render: () => <SpekoQueryFixture><TaskConnectionFailure bound /></SpekoQueryFixture>,
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
await expect(canvas.getByRole("alert")).toHaveTextContent("Voice connections could not be loaded.");
await expect(await canvas.findByRole("alert")).toHaveTextContent("Voice connections could not be loaded.");
canvas.getByRole("button", { name: "Retry voice connections" }).focus();
await userEvent.keyboard("{Enter}");
await expect(canvas.getByRole("button", { name: `Talk to ${spekoAgent.name}` })).toBeVisible();
await expect(canvas.queryByRole("alert")).not.toBeInTheDocument();
await expect(canvas.getByRole("button", { name: `Talk to ${spekoAgent.name}` })).toHaveFocus();
await waitFor(() => expect(canvas.getByRole("button", { name: `Talk to ${spekoAgent.name}` })).toHaveFocus());
},
};
@@ -1,9 +1,13 @@
import type {Meta, StoryObj} from "@storybook/react-vite";
import {useState} from "react";
import {expect, userEvent, within} from "storybook/test";
import {SpekoIncomingCallCard} from "@/components/voice/SpekoIncomingCalls";
import {useLayoutEffect, useState} from "react";
import {expect, userEvent, waitFor, within} from "storybook/test";
import {SpekoIncomingCalls, SpekoIncomingCallCard} from "@/components/voice/SpekoIncomingCalls";
import type {VoiceInboundCall} from "@paperclipai/shared";
import {voiceStoryLifecycle} from "../../fixtures/voiceStoryLifecycle";
import {voicePhoneApi} from "@/api/voicePhone";
import {issuesApi} from "@/api/issues";
import {storybookIssues} from "../../fixtures/paperclipData";
import {SpekoQueryFixture, spekoCompanyId, spekoEndpoint, spekoAgent} from "../../fixtures/spekoNative";
const call: VoiceInboundCall = {id: "incoming", state: "awaiting_approval", approvalCode: "123456", createdAt: "2026-10-07T17:00:00Z", expiresAt: "2026-10-07T17:02:00Z", sessionId: null};
const meta = {...voiceStoryLifecycle, title: "Connections/Speko/Live phone approval", component: SpekoIncomingCallCard, args: {call, onDecide: () => {}}, parameters: {layout: "padded"}} satisfies Meta<typeof SpekoIncomingCallCard>;
export default meta;
@@ -23,3 +27,30 @@ export const GuestIntake: Story = {args: {call: {...call, state: "guest_intake",
function PublicInteractive() {const [value,setValue] = useState<VoiceInboundCall>({...call, state: "guest_intake", intakeIssueId: "intake-task"}); return <SpekoIncomingCallCard call={value} onDecide={() => setValue({...value,state: "ended"})} />;}
export const PublicKeyboardEnd: Story = {render: () => <PublicInteractive />, play: async ({canvasElement}) => {const c=within(canvasElement); c.getByRole("button", {name: "End call"}).focus(); await userEvent.keyboard("{Enter}"); await expect(c.getByRole("heading", {name: "Caller hung up"})).toHaveFocus();}};
function TaskRequestFailure() {
const [ready, setReady] = useState(false);
useLayoutEffect(() => {
const originalIncoming = voicePhoneApi.incoming, originalTasks = issuesApi.list;
let requests = 0;
voicePhoneApi.incoming = async () => [call];
issuesApi.list = async () => {
if (!requests++) throw new Error("Fixture unavailable");
return [{...storybookIssues[0]!, id: "ready-task", status: "todo" as const, identifier: "PAP-42", title: "Ready existing conversation"}];
};
setReady(true);
return () => { voicePhoneApi.incoming = originalIncoming; issuesApi.list = originalTasks; };
}, []);
return ready ? <SpekoIncomingCalls companyId={spekoCompanyId} endpointId={spekoEndpoint.id} agentId={spekoAgent.id} /> : null;
}
export const TaskListFailureAndRecovery: Story = {
render: () => <SpekoQueryFixture><TaskRequestFailure /></SpekoQueryFixture>,
play: async ({canvasElement}) => {
const canvas = within(canvasElement);
await expect(await canvas.findByRole("alert")).toHaveTextContent("Task list could not be loaded");
const retry = canvas.getByRole("button", {name: "Retry tasks"}); retry.focus();
await userEvent.keyboard("{Enter}");
await expect(await canvas.findByRole("option", {name: "PAP-42 · Ready existing conversation"})).toBeVisible();
await waitFor(() => expect(canvas.queryByRole("alert")).not.toBeInTheDocument());
},
};