Merge branch 'codex/speko-voice-ui' into codex/speko-voice-qualification

* codex/speko-voice-ui:
  fix: finish Speko request recovery and setup footer
  fix: preserve voice reply ordering and reject unavailable work
This commit is contained in:
Dotta committed 2026-10-09 16:34:10 -05:00
commit d91210cc0f
11 files changed
+117 -19

No files matched your search

@@ -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);
@@ -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<string, unknown>;
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<boolean>`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.
@@ -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());
},
};