diff --git a/ui/src/components/voice/SpekoIncomingCalls.test.tsx b/ui/src/components/voice/SpekoIncomingCalls.test.tsx new file mode 100644 index 00000000000..14d7edb92ef --- /dev/null +++ b/ui/src/components/voice/SpekoIncomingCalls.test.tsx @@ -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());} + 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(); + }); +}); diff --git a/ui/src/components/voice/SpekoIncomingCalls.tsx b/ui/src/components/voice/SpekoIncomingCalls.tsx index c9cfc583850..9bc89f3e13f 100644 --- a/ui/src/components/voice/SpekoIncomingCalls.tsx +++ b/ui/src/components/voice/SpekoIncomingCalls.tsx @@ -36,7 +36,8 @@ export function SpekoIncomingCalls({companyId, endpointId, agentId}: {companyId: const [decision, setDecision] = useState(); 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
{query.error &&

Incoming call approval is unavailable. {query.error.message}

}{!query.error && [...(query.data ?? []).filter(call => call.id !== decision?.id), ...(decision ? [decision] : [])].map(call => !["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})} />)}
; + return
{needsTaskSelection && tasks.isError &&

Task list could not be loaded. Retry to choose an existing task.

}{query.error &&

Incoming call approval is unavailable. {query.error.message}

}{!query.error && [...(query.data ?? []).filter(call => call.id !== decision?.id), ...(decision ? [decision] : [])].map(call => !["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})} />)}
; } diff --git a/ui/src/components/voice/SpekoProviderSetup.tsx b/ui/src/components/voice/SpekoProviderSetup.tsx index 3a63f93302f..a1aaacd8273 100644 --- a/ui/src/components/voice/SpekoProviderSetup.tsx +++ b/ui/src/components/voice/SpekoProviderSetup.tsx @@ -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; onChange(values: Record): void; onConnect(values: Record): 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 &&

Configure a public HTTPS callback origin for Paperclip first. Local instances need an explicitly configured tunnel or reverse proxy.

} {reachable &&

Callback: {callbackUrl}

}

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.

- + {onSaveExit ? :
} ; } diff --git a/ui/src/components/voice/TaskVoiceLauncher.test.tsx b/ui/src/components/voice/TaskVoiceLauncher.test.tsx index 9f03aba14cc..50c789c977d 100644 --- a/ui/src/components/voice/TaskVoiceLauncher.test.tsx +++ b/ui/src/components/voice/TaskVoiceLauncher.test.tsx @@ -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(); diff --git a/ui/src/components/voice/TaskVoiceLauncher.tsx b/ui/src/components/voice/TaskVoiceLauncher.tsx index 3c7962a6758..370ff8a2504 100644 --- a/ui/src/components/voice/TaskVoiceLauncher.tsx +++ b/ui/src/components/voice/TaskVoiceLauncher.tsx @@ -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(null); + const launcher = useRef(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 ?

Voice connections could not be loaded.

- +
: null; if (!endpoint && connectionError) return
{connectionError}
; if (!endpoint) return boundEndpointId ?

{connections.isPending ? "Loading voice connection…" : "Voice is unavailable. Check the Speko connection in Apps."}

: null; diff --git a/ui/src/pages/apps/chat/ChatEndpointSetup.tsx b/ui/src/pages/apps/chat/ChatEndpointSetup.tsx index fdfd71b6b7f..19e864d0bf6 100644 --- a/ui/src/pages/apps/chat/ChatEndpointSetup.tsx +++ b/ui/src/pages/apps/chat/ChatEndpointSetup.tsx @@ -670,7 +670,7 @@ function ChatSdkEndpointSetup() { onSaveExit={() => navigate("/apps")} /> )} - {step !== 0 && !isSlack && !(provider === "speko" && step === tryStep) &&
+ {step !== 0 && !isSlack && provider !== "speko" &&
@@ -898,7 +898,7 @@ function ProviderConnectStep({ null, 2, ); - if (provider === "speko") return onAction(repairing ? "reconnect" : "configure", values)} callbackUrl={endpoint.setup?.webhookUrl} pending={pending} repairing={repairing} />; + if (provider === "speko") return 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 ; if (provider === "discord") { const applicationId = credentials.applicationId?.trim() ?? ""; diff --git a/ui/storybook/stories/speko-provider-setup.stories.tsx b/ui/storybook/stories/speko-provider-setup.stories.tsx index dc0944c2ccd..1b1cfba4697 100644 --- a/ui/storybook/stories/speko-provider-setup.stories.tsx +++ b/ui/storybook/stories/speko-provider-setup.stories.tsx @@ -6,7 +6,7 @@ import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle"; function Fixture(props: Partial) { const [credentials, setCredentials] = useState(props.credentials ?? {}); const [connected, setConnected] = useState(false); - return connected ?

Credentials saved. Continue to the test conversation.

: { if (!props.repairing && !values.signingSecret?.startsWith("whsec_")) throw new Error("Missing signing secret"); setConnected(true); }} />; + return connected ?

Credentials saved. Continue to the test conversation.

: {}} 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 = { ...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"); diff --git a/ui/storybook/stories/speko-task-launcher.stories.tsx b/ui/storybook/stories/speko-task-launcher.stories.tsx index a001969cadb..671aa436f39 100644 --- a/ui/storybook/stories/speko-task-launcher.stories.tsx +++ b/ui/storybook/stories/speko-task-launcher.stories.tsx @@ -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: () => , 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()); }, }; diff --git a/ui/storybook/stories/speko/incoming-call.stories.tsx b/ui/storybook/stories/speko/incoming-call.stories.tsx index 43c92f45bea..fcf59519273 100644 --- a/ui/storybook/stories/speko/incoming-call.stories.tsx +++ b/ui/storybook/stories/speko/incoming-call.stories.tsx @@ -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; export default meta; @@ -23,3 +27,30 @@ export const GuestIntake: Story = {args: {call: {...call, state: "guest_intake", function PublicInteractive() {const [value,setValue] = useState({...call, state: "guest_intake", intakeIssueId: "intake-task"}); return setValue({...value,state: "ended"})} />;} export const PublicKeyboardEnd: Story = {render: () => , 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 ? : null; +} +export const TaskListFailureAndRecovery: Story = { + render: () => , + 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()); + }, +};