diff --git a/ui/src/api/voiceSessions.test.ts b/ui/src/api/voiceSessions.test.ts new file mode 100644 index 00000000000..dd879339547 --- /dev/null +++ b/ui/src/api/voiceSessions.test.ts @@ -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); +}); diff --git a/ui/src/api/voiceSessions.ts b/ui/src/api/voiceSessions.ts index fda39017ac9..ce153e802b3 100644 --- a/ui/src/api/voiceSessions.ts +++ b/ui/src/api/voiceSessions.ts @@ -13,6 +13,6 @@ export const voiceSessionsApi = { return api.post(`${base(companyId)}/${encodeURIComponent(sessionId)}/end`, {}); }, notification(companyId: string, sessionId: string) { - return api.get(`${base(companyId)}/${encodeURIComponent(sessionId)}/notification`, { cache: "no-store" }); + return api.get(`${base(companyId)}/${encodeURIComponent(sessionId)}/notification`, { cache: "no-store", signal: AbortSignal.timeout(10_000) }); }, }; diff --git a/ui/src/components/voice/TaskVoiceLauncher.test.tsx b/ui/src/components/voice/TaskVoiceLauncher.test.tsx new file mode 100644 index 00000000000..9f03aba14cc --- /dev/null +++ b/ui/src/components/voice/TaskVoiceLauncher.test.tsx @@ -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: () =>

Active voice controls

})); + +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()); + } + 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"); + }); +}); diff --git a/ui/src/components/voice/TaskVoiceLauncher.tsx b/ui/src/components/voice/TaskVoiceLauncher.tsx index 1bba282e40a..20326644f48 100644 --- a/ui/src/components/voice/TaskVoiceLauncher.tsx +++ b/ui/src/components/voice/TaskVoiceLauncher.tsx @@ -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 ?
+

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; return
+ {connectionError} {!open ?
{candidates.length > 1 && } diff --git a/ui/storybook/stories/speko-task-launcher.stories.tsx b/ui/storybook/stories/speko-task-launcher.stories.tsx index 255fd5208e5..eb37b62f260 100644 --- a/ui/storybook/stories/speko-task-launcher.stories.tsx +++ b/ui/storybook/stories/speko-task-launcher.stories.tsx @@ -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 ? : null; +} +export const ConnectionLoadFailure: Story = { render: () => }; +export const BoundConnectionRecovery: Story = { + render: () => , + 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(); + }, +};