diff --git a/server/src/__tests__/voice-session-store.integration.test.ts b/server/src/__tests__/voice-session-store.integration.test.ts index b6b7ad6c80a..9f41a9bae6c 100644 --- a/server/src/__tests__/voice-session-store.integration.test.ts +++ b/server/src/__tests__/voice-session-store.integration.test.ts @@ -83,6 +83,14 @@ const support = await getEmbeddedPostgresTestSupport(); await expect(restarted.runTool({ ...request, fingerprint: "changed" })).rejects.toMatchObject({ status: 409 }); }); + it("rejects Backlog voice work before claiming that it was accepted", async () => { + const f = await fixture(); + await db.update(issues).set({status: "backlog"}).where(eq(issues.id, f.issueId)); + await expect(f.store.runTool(f.toolInput("submit_request", {text: "Inspect disk space"}))).rejects.toMatchObject({status: 409, message: "Move this task to Todo in Paperclip before requesting voice work."}); + expect(await db.select().from(chatDeliveries).where(eq(chatDeliveries.endpointId, f.endpointId))).toHaveLength(0); + expect(await db.select().from(chatVoiceToolCalls).where(eq(chatVoiceToolCalls.sessionId, f.sessionId))).toHaveLength(0); + }); + it("delivers urgent live-call guidance only after accepted work and retires it after hangup or revocation", async () => { const f = await fixture(), scope = { companyId: f.companyId, issueId: f.issueId, agentId: f.agentId }; expect(await liveVoiceExecutionGuidance(db, scope)).toBeNull(); @@ -504,6 +512,8 @@ const support = await getEmbeddedPostgresTestSupport(); it("sends long approved phone answers as durable ordered parts and resumes after a rate limit", async () => { const f = await pushFixture(), text = "😀 answer ".repeat(4000) + "FINAL"; await db.update(chatPublications).set({payload: {text}}).where(eq(chatPublications.id, f.publication.id)); + const [later] = await db.insert(chatPublications).values({companyId: f.companyId, endpointId: f.endpointId, conversationId: f.conversationId, issueId: f.issueId, idempotencyKey: randomUUID(), state: "published", payload: {text: "Later answer B"}}).returning(); + await f.store.enqueuePublication(f.companyId, later.id); f.transport.sendCallMessage.mockResolvedValueOnce({messageId: "part-0"}).mockRejectedValueOnce(new SpekoProviderError("provider_unavailable", false, 429)); await f.push(); const [reply] = await db.select().from(chatVoiceReplies).where(eq(chatVoiceReplies.publicationId, f.publication.id)); @@ -521,7 +531,7 @@ const support = await getEmbeddedPostgresTestSupport(); await voiceSessionService(db, {allowLocalBoard: false, credentials: f.credentials, provider: () => f.transport, onQuestionAnswered: vi.fn()}).pushReplies(25, f.companyId, f.endpointId); await f.push(); const calls = f.transport.sendCallMessage.mock.calls; - expect(calls).toHaveLength(4); expect(calls[1]?.[1]).toBe(calls[2]?.[1]); + expect(calls).toHaveLength(5); expect(calls[4]?.[1]).toBe("Later answer B"); expect(calls[1]?.[1]).toBe(calls[2]?.[1]); expect([calls[0]![1], calls[2]![1], calls[3]![1]].join("")).toBe(text); for (const call of calls) {expect(call[1].length).toBeLessThanOrEqual(16_000); expect(/^[\uDC00-\uDFFF]|[\uD800-\uDBFF]$/.test(call[1])).toBe(false);} const [delivered] = await db.select().from(chatVoiceReplies).where(eq(chatVoiceReplies.id, reply.id)); @@ -530,6 +540,8 @@ const support = await getEmbeddedPostgresTestSupport(); it("does not retry an uncertain long-answer part or send its suffix", async () => { const f = await pushFixture(); await db.update(chatPublications).set({payload: {text: "answer ".repeat(5000)}}).where(eq(chatPublications.id, f.publication.id)); + const [later] = await db.insert(chatPublications).values({companyId: f.companyId, endpointId: f.endpointId, conversationId: f.conversationId, issueId: f.issueId, idempotencyKey: randomUUID(), state: "published", payload: {text: "Later answer B"}}).returning(); + await f.store.enqueuePublication(f.companyId, later.id); f.transport.sendCallMessage.mockResolvedValueOnce({messageId: "part-0"}).mockRejectedValueOnce(new SpekoProviderError("provider_unavailable", true)); await f.push(); await f.push(); expect(f.transport.sendCallMessage).toHaveBeenCalledTimes(2); diff --git a/server/src/services/voice/voice-session-store.ts b/server/src/services/voice/voice-session-store.ts index 59a698c4aae..d9ad570ace9 100644 --- a/server/src/services/voice/voice-session-store.ts +++ b/server/src/services/voice/voice-session-store.ts @@ -317,6 +317,7 @@ export function voiceSessionStore(db: Db, options: { allowLocalBoard: boolean; n if (replay) throw conflict("Voice webhook id was already used for a different tool call"); let deliveryId: string | null = null, response: Record; if (input.envelope.tool === "submit_request") { + if (context.task.status === "backlog") throw conflict("Move this task to Todo in Paperclip before requesting voice work."); if (session.callerAuthority === "guest_intake") { const requests = await tx.select({id: chatVoiceToolCalls.id}).from(chatVoiceToolCalls).where(and(eq(chatVoiceToolCalls.sessionId, session.id), eq(chatVoiceToolCalls.tool, "submit_request"))).limit(20); if (requests.length >= 20) throw conflict("This call has reached its message limit. Continue in Paperclip."); @@ -347,9 +348,13 @@ export function voiceSessionStore(db: Db, options: { allowLocalBoard: boolean; n // The durable delivered marker is authoritative. A later publication // can finish before an earlier stream; a caller cursor must not hide // that older, still-unclaimed answer when it eventually publishes. - const available = await tx.select({ reply: chatVoiceReplies, payload: chatPublications.payload }).from(chatVoiceReplies).innerJoin(chatPublications, and(eq(chatPublications.id, chatVoiceReplies.publicationId), eq(chatPublications.companyId, session.companyId))) - .where(and(eq(chatVoiceReplies.sessionId, session.id), eq(chatVoiceReplies.companyId, session.companyId), repeat ? sql`${chatVoiceReplies.deliveredAt} is not null` : and(isNull(chatVoiceReplies.deliveredAt), sql`not exists (select 1 from chat_actions a where a.company_id = ${session.companyId} and a.endpoint_id = ${session.endpointId} and a.kind = 'speko_voice_reply_push' and a.payload->>'replyId' = ${chatVoiceReplies.id}::text and (a.status in ('dispatching', 'unknown') or (a.status = 'completed' and a.payload->>'questionNotification' = 'false')))`), eq(chatPublications.endpointId, session.endpointId), eq(chatPublications.conversationId, session.conversationId), eq(chatPublications.issueId, session.issueId), eq(chatPublications.state, "published"))) + const available = await tx.select({ reply: chatVoiceReplies, payload: chatPublications.payload, pushBlocked: sql`exists (select 1 from chat_actions a where a.company_id = ${session.companyId} and a.endpoint_id = ${session.endpointId} and a.kind = 'speko_voice_reply_push' and a.payload->>'replyId' = ${chatVoiceReplies.id}::text and (a.status in ('dispatching', 'unknown') or (a.status = 'completed' and a.payload->>'questionNotification' = 'false')))` }).from(chatVoiceReplies).innerJoin(chatPublications, and(eq(chatPublications.id, chatVoiceReplies.publicationId), eq(chatPublications.companyId, session.companyId))) + .where(and(eq(chatVoiceReplies.sessionId, session.id), eq(chatVoiceReplies.companyId, session.companyId), repeat ? sql`${chatVoiceReplies.deliveredAt} is not null` : isNull(chatVoiceReplies.deliveredAt), eq(chatPublications.endpointId, session.endpointId), eq(chatPublications.conversationId, session.conversationId), eq(chatPublications.issueId, session.issueId), eq(chatPublications.state, "published"))) .orderBy(repeat ? desc(chatVoiceReplies.deliveredAt) : asc(chatVoiceReplies.cursor), desc(chatVoiceReplies.cursor)).limit(repeat ? 1 : 8); + // Never skip a partly pushed answer to retrieve later replies. The + // accepted prefix cannot be replayed, and its suffix remains ordered. + const pushBoundary = available.findIndex(row => row.pushBlocked); + if (!repeat && pushBoundary >= 0) available.splice(pushBoundary); // Deliver a bounded burst in one voice turn. Separate typed hints would // interrupt the preceding answer. Stop at a question so later answers // cannot displace the clarification the caller must respond to. 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()); + }, +};