fix(speko): share connection cache across task voice controls

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-13 15:56:55 -05:00
1 parent d6a2675a72
commit b5684d9a42
4 files changed
+38 -5

No files matched your search

@@ -4,6 +4,7 @@ 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 { VoiceCallContext } from "./VoiceCallContext";
import { queryKeys } from "@/lib/queryKeys";
import { TaskVoiceLauncher } from "./TaskVoiceLauncher";
import { spekoEndpoint } from "../../../storybook/support/speko/spekoNative";
const mocks = vi.hoisted(() => ({ list: vi.fn() }));
@@ -15,7 +16,7 @@ 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 } } });
root = createRoot(container); client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: 30_000 } } });
});
afterEach(async () => { await act(async () => root.unmount()); client.clear(); container.remove(); });
async function render(bound = false, active?: boolean) {
@@ -47,13 +48,24 @@ describe("task voice connection failures", () => {
});
expect(container.querySelector('select')?.value).toBe("second");
});
it("updates the mounted launcher after shared connection pause and resume invalidation", async () => {
mocks.list.mockResolvedValue([spekoEndpoint]); await render(true);
await vi.waitFor(() => expect(container.textContent).toContain(`Talk to ${spekoEndpoint.assignedAgentName}`));
mocks.list.mockResolvedValue([{...spekoEndpoint, status: "paused"}]);
await act(async () => { await client.invalidateQueries({queryKey: queryKeys.chatEndpoints.list("company")}); });
await vi.waitFor(() => expect(container.textContent).toContain("Voice is unavailable"));
expect(container.textContent).not.toContain(`Talk to ${spekoEndpoint.assignedAgentName}`);
mocks.list.mockResolvedValue([spekoEndpoint]);
await act(async () => { await client.invalidateQueries({queryKey: queryKeys.chatEndpoints.list("company")}); });
await vi.waitFor(() => expect(container.textContent).toContain(`Talk to ${spekoEndpoint.assignedAgentName}`));
});
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 act(async () => { await client.refetchQueries({queryKey: queryKeys.chatEndpoints.list("company")}); });
await vi.waitFor(() => expect(container.querySelector('[role="alert"]')).not.toBeNull());
expect(container.textContent).toContain("Active voice controls");
});
@@ -1,5 +1,6 @@
import { useContext, useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { queryKeys } from "@/lib/queryKeys";
import { chatEndpointsApi } from "@/api/chatEndpoints";
import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled";
import { Button } from "@/components/ui/button";
@@ -11,7 +12,7 @@ export function TaskVoiceLauncher({ companyId, issueId, agentId, boundEndpointId
const host = useContext(VoiceCallContext), previouslyActive = 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) });
const connections = useQuery({ queryKey: queryKeys.chatEndpoints.list(companyId), queryFn: () => chatEndpointsApi.list(companyId), enabled: enabled && Boolean(agentId || boundEndpointId) });
useEffect(() => {
if (previouslyActive.current && !host?.active && open) { setOpen(false); restoreFocus.current = true; }
previouslyActive.current = Boolean(host?.active);
@@ -2,6 +2,7 @@ import type { Meta, StoryObj } from "@storybook/react-vite";
import { expect, userEvent, waitFor, within } from "storybook/test";
import { VoiceCallContext } from "@/components/voice/VoiceCallContext";
import { Button } from "@/components/ui/button";
import { queryKeys } from "@/lib/queryKeys";
import { TaskVoiceLauncher } from "@/components/voice/TaskVoiceLauncher";
import { AgentChannelsPanel } from "@/components/chat/AgentChannelsPanel";
import { ExternallyConnectedTaskBanner } from "@/components/chat/ExternallyConnectedTaskBanner";
@@ -44,7 +45,7 @@ function TaskConnectionFailure({ bound = false }: { bound?: boolean }) {
useLayoutEffect(() => {
const original = chatEndpointsApi.list;
chatEndpointsApi.list = async () => [spekoEndpoint];
const queryKey = ["task-voice-endpoints", spekoCompanyId];
const queryKey = queryKeys.chatEndpoints.list(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" });
@@ -86,3 +87,23 @@ export const PersonaAfterPanelClose: Story = {
await expect(canvas.getByRole("combobox", {name: "Voice persona"})).toHaveValue("second");
},
};
function SharedConnectionState() {
const client = useQueryClient();
return <><TaskVoiceLauncher {...props} boundEndpointId={spekoEndpoint.id} />
<Button onClick={() => client.setQueryData(queryKeys.chatEndpoints.list(spekoCompanyId), [{...spekoEndpoint, status: "paused"}])}>Pause fixture connection</Button>
<Button onClick={() => client.setQueryData(queryKeys.chatEndpoints.list(spekoCompanyId), [spekoEndpoint])}>Resume fixture connection</Button>
</>;
}
export const SharedPauseResume: Story = {
render: () => <SpekoQueryFixture><SharedConnectionState /></SpekoQueryFixture>,
play: async ({canvasElement}) => {
const canvas = within(canvasElement);
await expect(canvas.getByRole("button", {name: `Talk to ${spekoAgent.name}`})).toBeVisible();
await userEvent.click(canvas.getByRole("button", {name: "Pause fixture connection"}));
await expect(canvas.getByText("Voice is unavailable. Check the Speko connection in Apps.")).toBeVisible();
await expect(canvas.queryByRole("button", {name: `Talk to ${spekoAgent.name}`})).not.toBeInTheDocument();
await userEvent.click(canvas.getByRole("button", {name: "Resume fixture connection"}));
await expect(canvas.getByRole("button", {name: `Talk to ${spekoAgent.name}`})).toBeVisible();
},
};
@@ -18,7 +18,6 @@ export function SpekoQueryFixture({ children, endpoints = [spekoEndpoint], enabl
const client = new QueryClient({ defaultOptions: { queries: { staleTime: Infinity, retry: false, refetchOnMount: false, refetchOnWindowFocus: false } } });
client.setQueryData(queryKeys.instance.experimentalSettings, { enableChatConnectors: enabled });
client.setQueryData(queryKeys.chatEndpoints.list(spekoCompanyId), endpoints);
client.setQueryData(["task-voice-endpoints", spekoCompanyId], endpoints);
for (const endpoint of endpoints) client.setQueryData(queryKeys.chatEndpoints.detail(endpoint.id), endpoint);
return client;
});