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() ?? "";