mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-06 13:09:52 +08:00
Merge #2420 onto the shared speech player
This commit is contained in:
@@ -35,11 +35,13 @@ export function PlayAudioButton({
|
||||
conversationKey,
|
||||
autoPlayFresh,
|
||||
selection = false,
|
||||
playbackRate = 1,
|
||||
className,
|
||||
}: {
|
||||
content: string
|
||||
conversationKey?: string
|
||||
autoPlayFresh: boolean
|
||||
playbackRate?: number
|
||||
selection?: boolean
|
||||
className?: string
|
||||
}) {
|
||||
@@ -47,6 +49,11 @@ export function PlayAudioButton({
|
||||
const { autoplayEnabled } = useVoiceAutoplay(conversationKey)
|
||||
const [state, setState] = useState<'idle' | 'loading' | 'playing'>('idle')
|
||||
const audioRef = useRef<HTMLAudioElement | null>(null)
|
||||
const rateRef = useRef(playbackRate)
|
||||
useEffect(() => {
|
||||
rateRef.current = playbackRate
|
||||
if (audioRef.current) audioRef.current.playbackRate = playbackRate
|
||||
}, [playbackRate])
|
||||
const urlRef = useRef<string | null>(null)
|
||||
const abortRef = useRef<AbortController | null>(null)
|
||||
const genRef = useRef(0)
|
||||
@@ -125,6 +132,7 @@ export function PlayAudioButton({
|
||||
urlRef.current = url
|
||||
audio.src = url
|
||||
audio.load()
|
||||
audio.playbackRate = rateRef.current
|
||||
audio.onended = () => {
|
||||
if (gen !== genRef.current) return
|
||||
setState('idle')
|
||||
|
||||
@@ -64,6 +64,8 @@ import {
|
||||
} from "@/components/chat/GeneratedOutputFileActions";
|
||||
import { PlayAudioButton } from "@/components/voice/SpeechButton";
|
||||
export { PlayAudioButton } from "@/components/voice/SpeechButton";
|
||||
import { activeWorkspaceId } from "@/lib/workspace-scope";
|
||||
import { useVoicePlaybackRate, VOICE_PLAYBACK_RATES } from "@/hooks/useVoicePlaybackRate";
|
||||
import { extractMathAnimatorResult } from "@/lib/math-animator-types";
|
||||
import { extractVideoLessonResult } from "@/lib/video-lesson-types";
|
||||
import {
|
||||
@@ -2261,6 +2263,10 @@ export const ChatMessageList = memo(function ChatMessageList({
|
||||
}
|
||||
}
|
||||
|
||||
const { rate: voiceRate, setRate: setVoiceRate } = useVoicePlaybackRate(
|
||||
sessionId ? JSON.stringify([activeWorkspaceId(), sessionId]) : undefined,
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{messageRows.map(({ msg, originalIndex, pairedUserMessage }, rowIndex) => {
|
||||
@@ -2480,13 +2486,28 @@ export const ChatMessageList = memo(function ChatMessageList({
|
||||
/>
|
||||
)}
|
||||
{showActions && !compactActions && (
|
||||
<PlayAudioButton
|
||||
content={msg.content}
|
||||
conversationKey={sessionId ?? undefined}
|
||||
autoPlayFresh={
|
||||
isLastAssistant && freshlyCompletedIndex === i
|
||||
}
|
||||
/>
|
||||
<>
|
||||
<PlayAudioButton
|
||||
playbackRate={voiceRate}
|
||||
content={msg.content}
|
||||
conversationKey={sessionId ?? undefined}
|
||||
autoPlayFresh={
|
||||
isLastAssistant && freshlyCompletedIndex === i
|
||||
}
|
||||
/>
|
||||
{i === lastRenderedAssistantIndex && (
|
||||
<select
|
||||
aria-label={t("Playback speed")}
|
||||
className="rounded bg-transparent px-1 text-xs text-[var(--muted-foreground)]"
|
||||
value={voiceRate}
|
||||
onChange={(event) => setVoiceRate(Number(event.target.value))}
|
||||
>
|
||||
{VOICE_PLAYBACK_RATES.map((rate) => (
|
||||
<option key={rate} value={rate}>{rate}×</option>
|
||||
))}
|
||||
</select>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
{/* One way to try a turn again. Where the surface can
|
||||
take the turn back into its composer, Retry does that
|
||||
|
||||
44
web/hooks/useVoicePlaybackRate.ts
Normal file
44
web/hooks/useVoicePlaybackRate.ts
Normal file
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { browserStorage } from "@/shared/storage";
|
||||
|
||||
export const VOICE_PLAYBACK_RATES = [0.75, 1, 1.25, 1.5, 2] as const;
|
||||
|
||||
function normalizeRate(value: number): number {
|
||||
return VOICE_PLAYBACK_RATES.some((rate) => rate === value) ? value : 1;
|
||||
}
|
||||
|
||||
function readRate(scopeKey?: string): number {
|
||||
if (!scopeKey) return 1;
|
||||
return normalizeRate(Number(browserStorage.readRaw("local", storageKey(scopeKey))));
|
||||
}
|
||||
|
||||
function storageKey(scopeKey: string): string {
|
||||
return `deeptutor.voicePlaybackRate:${scopeKey}`;
|
||||
}
|
||||
|
||||
interface VoicePlaybackRatePreference {
|
||||
rate: number;
|
||||
setRate: (rate: number) => void;
|
||||
}
|
||||
|
||||
/** Persist a conversation's playback rate in this browser. */
|
||||
export function useVoicePlaybackRate(scopeKey?: string): VoicePlaybackRatePreference {
|
||||
const [preference, setPreference] = useState(() => ({
|
||||
scopeKey,
|
||||
rate: readRate(scopeKey),
|
||||
}));
|
||||
|
||||
if (preference.scopeKey !== scopeKey) {
|
||||
setPreference({ scopeKey, rate: readRate(scopeKey) });
|
||||
}
|
||||
|
||||
function setRate(value: number) {
|
||||
const rate = normalizeRate(value);
|
||||
if (scopeKey) browserStorage.writeRaw("local", storageKey(scopeKey), String(rate));
|
||||
setPreference({ scopeKey, rate });
|
||||
}
|
||||
|
||||
return { rate: preference.rate, setRate };
|
||||
}
|
||||
@@ -1,23 +1,28 @@
|
||||
import { act, render, screen } from "@testing-library/react";
|
||||
import { act, render, renderHook, screen } from "@testing-library/react";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { PlayAudioButton } from "@/features/chat/messages/ChatMessageList";
|
||||
import { useVoicePlaybackRate } from "@/hooks/useVoicePlaybackRate";
|
||||
import { apiFetch } from "@/lib/api";
|
||||
import { notify } from "@/lib/notifications";
|
||||
import { initI18n } from "@/i18n/init";
|
||||
import { browserStorage } from "@/shared/storage";
|
||||
|
||||
const autoplay = vi.hoisted(() => ({ enabled: false }));
|
||||
|
||||
vi.mock("@/lib/api", async (original) => ({
|
||||
...(await original<typeof import("@/lib/api")>()),
|
||||
apiFetch: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/hooks/useVoiceAutoplay", () => ({
|
||||
useVoiceAutoplay: () => ({ autoplayEnabled: false }),
|
||||
useVoiceAutoplay: () => ({ autoplayEnabled: autoplay.enabled }),
|
||||
}));
|
||||
vi.mock("@/lib/notifications", () => ({ notify: vi.fn() }));
|
||||
initI18n("en");
|
||||
const instances: FakeAudio[] = [];
|
||||
class FakeAudio {
|
||||
src = "";
|
||||
playbackRate = 1;
|
||||
pause = vi.fn();
|
||||
play = vi.fn().mockResolvedValue(undefined);
|
||||
load = vi.fn();
|
||||
@@ -33,7 +38,7 @@ function installAudio() {
|
||||
Object.defineProperty(URL, "createObjectURL", { configurable: true, value: vi.fn(() => "blob:test") });
|
||||
Object.defineProperty(URL, "revokeObjectURL", { configurable: true, value: vi.fn() });
|
||||
}
|
||||
afterEach(() => { vi.unstubAllGlobals(); instances.length = 0; });
|
||||
afterEach(() => { vi.unstubAllGlobals(); vi.restoreAllMocks(); instances.length = 0; autoplay.enabled = false; });
|
||||
|
||||
it("switches between reply buttons without overlapping speech or a first-click prompt", async () => {
|
||||
installAudio();
|
||||
@@ -110,3 +115,71 @@ it("does not show a late speech error after playback is cancelled", async () =>
|
||||
await act(async () => { resolve({ detail: "Speech synthesis timed out." }); });
|
||||
expect(notify).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the latest rate after synthesis and changes active playback without refetching", async () => {
|
||||
installAudio();
|
||||
vi.mocked(apiFetch).mockClear();
|
||||
let resolve!: (response: Response) => void;
|
||||
vi.mocked(apiFetch).mockReturnValueOnce(new Promise<Response>((done) => { resolve = done; }));
|
||||
const { rerender } = render(<PlayAudioButton content="Hello" autoPlayFresh={false} />);
|
||||
await userEvent.setup().click(screen.getByRole("button", { name: "Play aloud" }));
|
||||
rerender(<PlayAudioButton content="Hello" autoPlayFresh={false} playbackRate={1.5} />);
|
||||
await act(async () => {
|
||||
resolve({ ok: true, blob: async () => new Blob(["audio"]) } as Response);
|
||||
});
|
||||
expect(instances[0].playbackRate).toBe(1.5);
|
||||
rerender(<PlayAudioButton content="Hello" autoPlayFresh={false} playbackRate={0.75} />);
|
||||
expect(instances[0].playbackRate).toBe(0.75);
|
||||
expect(instances[0].play).toHaveBeenCalledTimes(2);
|
||||
expect(apiFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("restores the rate per conversation and falls back for an invalid rate", () => {
|
||||
const { result, rerender, unmount } = renderHook(
|
||||
({ scope }) => useVoicePlaybackRate(scope),
|
||||
{ initialProps: { scope: "rate-test-a" } },
|
||||
);
|
||||
act(() => result.current.setRate(1.5));
|
||||
rerender({ scope: "rate-test-b" });
|
||||
expect(result.current.rate).toBe(1);
|
||||
act(() => result.current.setRate(2));
|
||||
unmount();
|
||||
const restored = renderHook(() => useVoicePlaybackRate("rate-test-a"));
|
||||
expect(restored.result.current.rate).toBe(1.5);
|
||||
act(() => restored.result.current.setRate(Number.NaN));
|
||||
expect(restored.result.current.rate).toBe(1);
|
||||
});
|
||||
|
||||
it("keeps autoplay at the selected rate without restarting when the rate changes", async () => {
|
||||
installAudio();
|
||||
autoplay.enabled = true;
|
||||
vi.mocked(apiFetch).mockClear();
|
||||
vi.mocked(apiFetch).mockResolvedValue({ ok: true, blob: async () => new Blob(["audio"]) } as Response);
|
||||
const { rerender } = render(<PlayAudioButton content="Hello" autoPlayFresh playbackRate={1.5} />);
|
||||
expect(await screen.findByRole("button", { name: "Stop" })).toBeVisible();
|
||||
expect(instances[0].playbackRate).toBe(1.5);
|
||||
rerender(<PlayAudioButton content="Hello" autoPlayFresh playbackRate={2} />);
|
||||
expect(instances[0].playbackRate).toBe(2);
|
||||
expect(instances[0].pause).not.toHaveBeenCalled();
|
||||
expect(apiFetch).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it("defaults to normal speed for corrupt storage and still changes speed when storage is unavailable", () => {
|
||||
vi.spyOn(browserStorage, "readRaw").mockReturnValue("corrupt");
|
||||
vi.spyOn(browserStorage, "writeRaw").mockReturnValue(false);
|
||||
const { result } = renderHook(() => useVoicePlaybackRate("unavailable-storage"));
|
||||
expect(result.current.rate).toBe(1);
|
||||
act(() => result.current.setRate(1.25));
|
||||
expect(result.current.rate).toBe(1.25);
|
||||
});
|
||||
|
||||
it("keeps an unsaved conversation's speed in memory without persisting it", () => {
|
||||
const write = vi.spyOn(browserStorage, "writeRaw");
|
||||
const { result, unmount } = renderHook(() => useVoicePlaybackRate());
|
||||
act(() => result.current.setRate(0.75));
|
||||
expect(result.current.rate).toBe(0.75);
|
||||
expect(write).not.toHaveBeenCalled();
|
||||
unmount();
|
||||
const fresh = renderHook(() => useVoicePlaybackRate());
|
||||
expect(fresh.result.current.rate).toBe(1);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user