mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-01 18:07:00 +01:00
fix(speko): restore persona selection and retire interrupted speech
Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
1 parent
7f2f5aa262
commit
f43733bc75
8 files changed
+60
-8
No files matched your search
@@ -3,6 +3,7 @@ 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 { VoiceCallContext } from "./VoiceCallContext";
|
||||
import { TaskVoiceLauncher } from "./TaskVoiceLauncher";
|
||||
import { spekoEndpoint } from "../../../storybook/support/speko/spekoNative";
|
||||
const mocks = vi.hoisted(() => ({ list: vi.fn() }));
|
||||
@@ -17,8 +18,8 @@ describe("task voice connection failures", () => {
|
||||
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>));
|
||||
async function render(bound = false, active?: boolean) {
|
||||
await act(async () => root.render(<QueryClientProvider client={client}><VoiceCallContext.Provider value={active === undefined ? null : { active, open: vi.fn() }}><TaskVoiceLauncher companyId="company" issueId="issue" agentId={spekoEndpoint.assignedAgentId} boundEndpointId={bound ? spekoEndpoint.id : undefined} /></VoiceCallContext.Provider></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);
|
||||
@@ -30,6 +31,22 @@ describe("task voice connection failures", () => {
|
||||
expect(container.querySelector('[role="alert"]')).toBeNull();
|
||||
expect(document.activeElement).toBe(container.querySelector('button'));
|
||||
});
|
||||
it("restores persona selection and keyboard focus after the hosted panel closes", async () => {
|
||||
mocks.list.mockResolvedValue([spekoEndpoint, {...spekoEndpoint, id: "second", botLabel: "Second persona"}]);
|
||||
await render(false, false);
|
||||
await vi.waitFor(() => expect(container.querySelector('select')).not.toBeNull());
|
||||
await act(async () => container.querySelector('button')!.click());
|
||||
expect(container.querySelector('select')).toBeNull();
|
||||
await render(false, true);
|
||||
await render(false, false);
|
||||
await vi.waitFor(() => expect(container.querySelector('select')).not.toBeNull());
|
||||
expect(document.activeElement).toBe(container.querySelector('button'));
|
||||
await act(async () => {
|
||||
const select = container.querySelector('select')!; select.value = "second";
|
||||
select.dispatchEvent(new Event("change", {bubbles: true}));
|
||||
});
|
||||
expect(container.querySelector('select')?.value).toBe("second");
|
||||
});
|
||||
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());
|
||||
|
||||
@@ -1,20 +1,26 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useContext, useEffect, useRef, useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { chatEndpointsApi } from "@/api/chatEndpoints";
|
||||
import { useChatConnectorsEnabled } from "@/hooks/useChatConnectorsEnabled";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { VoiceCallContext } from "./VoiceCallContext";
|
||||
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), restoreFocus = useRef(false);
|
||||
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) });
|
||||
useEffect(() => {
|
||||
if (previouslyActive.current && !host?.active && open) { setOpen(false); restoreFocus.current = true; }
|
||||
previouslyActive.current = Boolean(host?.active);
|
||||
}, [host?.active, open]);
|
||||
useEffect(() => {
|
||||
if (restoreFocus.current && !connections.isFetching && !connections.isError && launcher.current) {
|
||||
restoreFocus.current = false; launcher.current.focus();
|
||||
}
|
||||
}, [connections.data, connections.isFetching, connections.isError]);
|
||||
}, [connections.data, connections.isFetching, connections.isError, open]);
|
||||
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];
|
||||
|
||||
@@ -16,7 +16,7 @@ export function VoiceTranscript({ entries, agentName, unavailable = false }: Voi
|
||||
<li key={entry.id} className="flex min-w-0 flex-col gap-1">
|
||||
<span className="text-xs font-medium text-muted-foreground break-words">
|
||||
{entry.source === "user" ? "You" : entry.source === "application" ? "Paperclip" : agentName}
|
||||
{!entry.final && <span> · Speaking</span>}
|
||||
{!entry.final && !entry.interrupted && <span> · Speaking</span>}
|
||||
{entry.interrupted && <span> · Interrupted</span>}
|
||||
</span>
|
||||
<p className="whitespace-pre-wrap break-words text-sm">{entry.text}</p>
|
||||
|
||||
@@ -120,7 +120,7 @@ describe("voice media session lifecycle", () => {
|
||||
x.callbacks().onMessage({ source: "agent", text: "An interrupted answer, delayed fragment", segmentId: "old-answer", isFinal: false });
|
||||
await vi.advanceTimersByTimeAsync(1_500);
|
||||
expect(x.media.sendChatMessage).toHaveBeenCalledOnce();
|
||||
expect(x.controller.getSnapshot().transcript[0]?.final).toBe(false);
|
||||
expect(x.controller.getSnapshot().transcript[0]).toMatchObject({ final: false, interrupted: true });
|
||||
});
|
||||
it("clears queued hints when a call ends during the quiet period", async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
@@ -122,7 +122,7 @@ export function createVoiceSessionController(dependencies: VoiceSessionDependenc
|
||||
segmentId = fallback.id;
|
||||
fallbackSegments.set(update.source, { id: segmentId, final: fallback.final || update.isFinal, text: update.text });
|
||||
}
|
||||
const transcript = updateVoiceTranscript(snapshot.transcript, { ...update, segmentId }, segmentId);
|
||||
let transcript = updateVoiceTranscript(snapshot.transcript, { ...update, segmentId }, segmentId);
|
||||
const entry = transcript.find((item) => item.id === `${update.source}:${segmentId}`);
|
||||
const previous = snapshot.transcript.find((item) => item.id === entry?.id);
|
||||
// Active-speaker silence can occur in the middle of a streamed
|
||||
@@ -132,6 +132,7 @@ export function createVoiceSessionController(dependencies: VoiceSessionDependenc
|
||||
if (update.source === "user") {
|
||||
for (const id of unfinishedAgentSegments) interruptedAgentSegments.add(id);
|
||||
unfinishedAgentSegments.clear();
|
||||
transcript = transcript.map(item => item.source === "agent" && interruptedAgentSegments.has(item.id.slice("agent:".length)) ? { ...item, interrupted: true } : item);
|
||||
} else if (entry?.final || interruptedAgentSegments.has(segmentId)) unfinishedAgentSegments.delete(segmentId);
|
||||
else unfinishedAgentSegments.add(segmentId);
|
||||
noteActivity();
|
||||
|
||||
@@ -1,5 +1,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 { TaskVoiceLauncher } from "@/components/voice/TaskVoiceLauncher";
|
||||
import { AgentChannelsPanel } from "@/components/chat/AgentChannelsPanel";
|
||||
import { ExternallyConnectedTaskBanner } from "@/components/chat/ExternallyConnectedTaskBanner";
|
||||
@@ -64,3 +66,23 @@ export const BoundConnectionRecovery: Story = {
|
||||
await waitFor(() => expect(canvas.getByRole("button", { name: `Talk to ${spekoAgent.name}` })).toHaveFocus());
|
||||
},
|
||||
};
|
||||
|
||||
function PersonaRecovery() {
|
||||
const [active, setActive] = useState(false);
|
||||
return <VoiceCallContext.Provider value={{active, open: () => setActive(true)}}>
|
||||
<TaskVoiceLauncher {...props} />
|
||||
{active && <Button onClick={() => setActive(false)}>Close voice panel</Button>}
|
||||
</VoiceCallContext.Provider>;
|
||||
}
|
||||
export const PersonaAfterPanelClose: Story = {
|
||||
render: () => <SpekoQueryFixture endpoints={[spekoEndpoint, {...spekoEndpoint, id: "second", botLabel: "Second persona"}]}><PersonaRecovery /></SpekoQueryFixture>,
|
||||
play: async ({canvasElement}) => {
|
||||
const canvas = within(canvasElement);
|
||||
await userEvent.click(canvas.getByRole("button", {name: `Talk to ${spekoAgent.name}`}));
|
||||
await userEvent.click(canvas.getByRole("button", {name: "Start voice"}));
|
||||
await userEvent.click(canvas.getByRole("button", {name: "Close voice panel"}));
|
||||
await waitFor(() => expect(canvas.getByRole("button", {name: `Talk to ${spekoAgent.name}`})).toHaveFocus());
|
||||
await userEvent.selectOptions(canvas.getByRole("combobox", {name: "Voice persona"}), "second");
|
||||
await expect(canvas.getByRole("combobox", {name: "Voice persona"})).toHaveValue("second");
|
||||
},
|
||||
};
|
||||
@@ -1,4 +1,5 @@
|
||||
import { voiceStoryLifecycle } from "../../../support/speko/voiceStoryLifecycle";
|
||||
import { expect, within } from "storybook/test";
|
||||
import type { Meta, StoryObj } from "@storybook/react-vite";
|
||||
import { VoiceTranscript } from "@/components/voice/VoiceTranscript";
|
||||
|
||||
@@ -15,7 +16,11 @@ export const FinalSpeech: Story = { args: { entries: [{ id: "a", source: "user",
|
||||
export const OverlappingUpdates: Story = { args: { entries: [
|
||||
{ id: "a", source: "agent", text: "The order is scheduled for", final: false, interrupted: true },
|
||||
{ id: "b", source: "user", text: "Please check the revised address too.", final: true },
|
||||
] } };
|
||||
] }, play: async ({ canvasElement }) => {
|
||||
const canvas = within(canvasElement);
|
||||
await expect(canvas.getByText("· Interrupted")).toBeVisible();
|
||||
await expect(canvas.queryByText("· Speaking")).not.toBeInTheDocument();
|
||||
} };
|
||||
export const DelayedResult: Story = { args: { entries: [
|
||||
{ id: "a", source: "agent", text: "I’m checking that now.", final: true },
|
||||
{ id: "notification", source: "application", text: "A task update is available.", final: true },
|
||||
|
||||
@@ -139,6 +139,7 @@ function Frame({ children, width = "max-w-3xl" }: { children: React.ReactNode; w
|
||||
}
|
||||
|
||||
const meta: Meta = {
|
||||
excludeStories: ["makePreview"],
|
||||
id: "surfaces-team-catalog",
|
||||
title: "Agents and reusable capabilities/Team packages and installation/Surfaces/Team Catalog",
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user