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

* codex/speko-voice-ui:
  fix: recover live voice polling after stalled requests
  fix: surface task voice connection load failures
This commit is contained in:
Dotta committed 2026-10-09 16:14:58 -05:00
commit b551fe2a00
5 files changed
+96 -2

No files matched your search

+18
View File
@@ -0,0 +1,18 @@
import { afterEach, expect, it, vi } from "vitest";
import { voiceSessionsApi } from "./voiceSessions";
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
it("aborts a stuck notification fetch so the next poll can retrieve the saved answer", async () => {
const deadline = new AbortController();
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(deadline.signal);
const fetch = vi.fn().mockImplementationOnce((_url: string, init: RequestInit) => new Promise((_resolve, reject) => {
init.signal!.addEventListener("abort", () => reject(new DOMException("Aborted", "AbortError")), { once: true });
})).mockResolvedValueOnce(new Response(JSON.stringify({sessionId: "session", generation: 1, publicationId: "saved-answer", attempt: 0}), {headers: {"content-type": "application/json"}}));
vi.stubGlobal("fetch", fetch);
const stalled = voiceSessionsApi.notification("company", "session");
const rejected = expect(stalled).rejects.toMatchObject({name: "AbortError"});
expect(timeout).toHaveBeenCalledWith(10_000); deadline.abort(); await rejected;
timeout.mockReturnValue(new AbortController().signal);
await expect(voiceSessionsApi.notification("company", "session")).resolves.toMatchObject({publicationId: "saved-answer"});
expect(fetch).toHaveBeenCalledTimes(2);
});
+1 -1
View File
@@ -13,6 +13,6 @@ export const voiceSessionsApi = {
return api.post<VoiceSession>(`${base(companyId)}/${encodeURIComponent(sessionId)}/end`, {});
},
notification(companyId: string, sessionId: string) {
return api.get<VoiceSessionNotification | null>(`${base(companyId)}/${encodeURIComponent(sessionId)}/notification`, { cache: "no-store" });
return api.get<VoiceSessionNotification | null>(`${base(companyId)}/${encodeURIComponent(sessionId)}/notification`, { cache: "no-store", signal: AbortSignal.timeout(10_000) });
},
};
@@ -0,0 +1,41 @@
// @vitest-environment jsdom
import { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { TaskVoiceLauncher } from "./TaskVoiceLauncher";
import { spekoEndpoint } from "../../../storybook/fixtures/spekoNative";
const mocks = vi.hoisted(() => ({ list: vi.fn() }));
vi.mock("@/api/chatEndpoints", () => ({ chatEndpointsApi: { list: mocks.list } }));
vi.mock("@/hooks/useChatConnectorsEnabled", () => ({ useChatConnectorsEnabled: () => ({ enabled: true }) }));
vi.mock("./NativeVoiceConversation", () => ({ NativeVoiceConversation: () => <p>Active voice controls</p> }));
describe("task voice connection failures", () => {
let container: HTMLDivElement, root: Root, client: QueryClient;
beforeEach(() => {
vi.resetAllMocks(); container = document.createElement("div"); document.body.append(container);
root = createRoot(container); client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
});
afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); });
async function render(bound = false) {
await act(async () => root.render(<QueryClientProvider client={client}><TaskVoiceLauncher companyId="company" issueId="issue" agentId={spekoEndpoint.assignedAgentId} boundEndpointId={bound ? spekoEndpoint.id : undefined} /></QueryClientProvider>));
}
it.each([false, true])("shows a retryable request failure for bound=%s instead of a missing connection", async bound => {
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");
await act(async () => container.querySelector('button')!.click());
await vi.waitFor(() => expect(container.textContent).toContain(`Talk to ${spekoEndpoint.assignedAgentName}`));
expect(container.querySelector('[role="alert"]')).toBeNull();
});
it("keeps active controls mounted when a background connection refresh fails", async () => {
mocks.list.mockResolvedValue([spekoEndpoint]); await render();
await vi.waitFor(() => expect(container.querySelector('button')).not.toBeNull());
await act(async () => container.querySelector('button')!.click());
expect(container.textContent).toContain("Active voice controls");
mocks.list.mockRejectedValue(new Error("Offline"));
await act(async () => { await client.refetchQueries({queryKey: ["task-voice-endpoints", "company"]}); });
await vi.waitFor(() => expect(container.querySelector('[role="alert"]')).not.toBeNull());
expect(container.textContent).toContain("Active voice controls");
});
});
@@ -12,8 +12,14 @@ export function TaskVoiceLauncher({ companyId, issueId, agentId, boundEndpointId
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()}>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;
return <section aria-label="Task voice conversation" className="space-y-3 rounded-lg border border-border p-4">
{connectionError}
{!open ? <div className="flex flex-wrap items-center gap-3">
{candidates.length > 1 && <label className="flex min-w-0 max-w-full flex-col gap-2 text-sm">Voice persona<select aria-label="Voice persona" className="w-full min-w-0 max-w-full rounded-md border border-input bg-background p-2 text-sm" value={endpoint.id} onChange={(event) => setSelected(event.target.value)}>{candidates.map((entry) => <option key={entry.id} value={entry.id}>{entry.botLabel ?? entry.assignedAgentName}</option>)}</select></label>}
<Button variant="outline" onClick={() => setOpen(true)}>Talk to {endpoint.assignedAgentName}</Button>
@@ -4,7 +4,8 @@ import { TaskVoiceLauncher } from "@/components/voice/TaskVoiceLauncher";
import { AgentChannelsPanel } from "@/components/chat/AgentChannelsPanel";
import { ExternallyConnectedTaskBanner } from "@/components/chat/ExternallyConnectedTaskBanner";
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useLayoutEffect, useState } from "react";
import { chatEndpointsApi } from "@/api/chatEndpoints";
import { SpekoQueryFixture, spekoAgent, spekoCompanyId, spekoEndpoint } from "../fixtures/spekoNative";
import { voiceStoryLifecycle } from "../fixtures/voiceStoryLifecycle";
const props = { companyId: spekoCompanyId, issueId: "task-fixture", agentId: spekoAgent.id };
@@ -33,3 +34,31 @@ export const KeyboardOpen: Story = {
// Opening controls must not acquire a microphone or create a session.
},
};
/** Seed a failed query; retries resolve locally and never contact a provider. */
function TaskConnectionFailure({ bound = false }: { bound?: boolean }) {
const client = useQueryClient();
const [ready, setReady] = useState(false);
useLayoutEffect(() => {
const original = chatEndpointsApi.list;
chatEndpointsApi.list = async () => [spekoEndpoint];
const queryKey = ["task-voice-endpoints", spekoCompanyId];
client.removeQueries({ queryKey });
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 }); };
}, [client]);
return ready ? <TaskVoiceLauncher {...props} boundEndpointId={bound ? spekoEndpoint.id : undefined} /> : null;
}
export const ConnectionLoadFailure: Story = { render: () => <SpekoQueryFixture><TaskConnectionFailure /></SpekoQueryFixture> };
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.");
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();
},
};