Repository navigation
fix(web): keep voice-note processing owned by its recording #3464
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
vedanth-jadhav
wants to merge
3
commits into
CapSoftware:main
Choose a base branch
from
vedanth-jadhav:fix/web-voice-recorder-run-ownership
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
264 changes: 264 additions & 0 deletions
264
apps/web/__tests__/unit/voice-recorder-lifecycle.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,264 @@ | ||
| // @vitest-environment jsdom | ||
|
|
||
| import { act, createElement } from "react"; | ||
| import { createRoot, type Root } from "react-dom/client"; | ||
| import { afterEach, beforeEach, expect, it, vi } from "vitest"; | ||
| import { useVoiceRecorder } from "@/app/s/[videoId]/_components/timeline/recording/useVoiceRecorder"; | ||
|
|
||
| const mocks = vi.hoisted(() => ({ | ||
| mic: vi.fn(), | ||
| mixer: vi.fn(), | ||
| decode: vi.fn(), | ||
| })); | ||
| vi.mock("@cap/recorder-core/capture-streams", () => ({ | ||
| acquireMicStream: mocks.mic, | ||
| createAudioMixer: mocks.mixer, | ||
| })); | ||
| vi.mock( | ||
| "@/app/s/[videoId]/_components/timeline/recording/compute-waveform-peaks", | ||
| async (importOriginal) => ({ | ||
| ...(await importOriginal< | ||
| typeof import("@/app/s/[videoId]/_components/timeline/recording/compute-waveform-peaks") | ||
| >()), | ||
| decodeToPeaks: mocks.decode, | ||
| }), | ||
| ); | ||
| function deferred<T>() { | ||
| let resolve!: (value: T) => void; | ||
| const promise = new Promise<T>((done) => { | ||
| resolve = done; | ||
| }); | ||
| return { promise, resolve }; | ||
| } | ||
| class Track { | ||
| readyState = "live"; | ||
| stop = vi.fn(() => { | ||
| this.readyState = "ended"; | ||
| }); | ||
| getSettings() { | ||
| return { deviceId: "microphone" }; | ||
| } | ||
| } | ||
| class Stream { | ||
| constructor(readonly track = new Track()) {} | ||
| getTracks() { | ||
| return [this.track]; | ||
| } | ||
| getAudioTracks() { | ||
| return [this.track]; | ||
| } | ||
| } | ||
| class Recorder { | ||
| static isTypeSupported = () => true; | ||
| static startError: Error | null = null; | ||
| static pendingStops: Array<() => void> | null = null; | ||
| state: RecordingState = "inactive"; | ||
| mimeType = "audio/webm"; | ||
| ondataavailable: ((event: BlobEvent) => void) | null = null; | ||
| onstop: ((event: Event) => void) | null = null; | ||
| onerror: ((event: Event) => void) | null = null; | ||
| start() { | ||
| if (Recorder.startError) throw Recorder.startError; | ||
| this.state = "recording"; | ||
| } | ||
| stop() { | ||
| this.state = "inactive"; | ||
| const finish = () => { | ||
| const event = new Event("dataavailable"); | ||
| Object.defineProperty(event, "target", { value: this }); | ||
| Object.defineProperty(event, "data", { | ||
| value: new Blob(["audio"], { type: "audio/webm" }), | ||
| }); | ||
| this.ondataavailable?.(event as BlobEvent); | ||
| const stopped = new Event("stop"); | ||
| Object.defineProperty(stopped, "target", { value: this }); | ||
| this.onstop?.(stopped); | ||
| }; | ||
| if (Recorder.pendingStops) Recorder.pendingStops.push(finish); | ||
| else queueMicrotask(finish); | ||
| } | ||
| } | ||
| let root: Root; | ||
| let container: HTMLDivElement; | ||
| let mounted: boolean; | ||
| let recorder: ReturnType<typeof useVoiceRecorder>; | ||
| const onFinish = vi.fn(); | ||
| function mixer(stream = new Stream()) { | ||
| return { | ||
| context: {}, | ||
| stream, | ||
| close: vi.fn(async () => {}), | ||
| setMicStream: vi.fn(), | ||
| }; | ||
| } | ||
| beforeEach(async () => { | ||
| Recorder.startError = null; | ||
| Recorder.pendingStops = null; | ||
| vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); | ||
| vi.stubGlobal("MediaRecorder", Recorder); | ||
| onFinish.mockReset(); | ||
| mocks.mic.mockReset().mockImplementation(async () => new Stream()); | ||
| mocks.mixer.mockReset().mockImplementation(async () => mixer()); | ||
| mocks.decode.mockReset().mockResolvedValue([0.25, 1]); | ||
| container = document.createElement("div"); | ||
| document.body.append(container); | ||
| root = createRoot(container); | ||
| mounted = true; | ||
| function Harness() { | ||
| recorder = useVoiceRecorder({ onFinish, selectedMicId: null }); | ||
| return null; | ||
| } | ||
| await act(async () => root.render(createElement(Harness))); | ||
| }); | ||
| afterEach(async () => { | ||
| if (mounted) await unmount(); | ||
| container.remove(); | ||
| vi.restoreAllMocks(); | ||
| vi.unstubAllGlobals(); | ||
| }); | ||
| async function unmount() { | ||
| await act(async () => root.unmount()); | ||
| mounted = false; | ||
| } | ||
| async function beginDecoding() { | ||
| const decode = deferred<number[] | undefined>(); | ||
| mocks.decode.mockReturnValueOnce(decode.promise); | ||
| await act(async () => recorder.start()); | ||
| let stopping!: Promise<void>; | ||
| await act(async () => { | ||
| stopping = recorder.stop(); | ||
| }); | ||
| expect(mocks.decode).toHaveBeenCalledTimes(1); | ||
| return { decode, stopping }; | ||
| } | ||
|
|
||
| it.each(["cancel", "unmount"])( | ||
| "does not finish a voice note after %s during waveform decoding", | ||
| async (action) => { | ||
| const { decode, stopping } = await beginDecoding(); | ||
| if (action === "cancel") await act(async () => recorder.cancel()); | ||
| else await unmount(); | ||
| await act(async () => { | ||
| decode.resolve([1]); | ||
| await stopping; | ||
| }); | ||
| expect(onFinish).not.toHaveBeenCalled(); | ||
| }, | ||
| ); | ||
|
|
||
| it("does not finish an old take or reset the replacement while decoding completes", async () => { | ||
| const { decode, stopping } = await beginDecoding(); | ||
| await act(async () => recorder.cancel()); | ||
| await act(async () => recorder.start()); | ||
| expect(recorder.phase).toBe("recording"); | ||
| await act(async () => { | ||
| decode.resolve([1]); | ||
| await stopping; | ||
| }); | ||
| expect(onFinish).not.toHaveBeenCalled(); | ||
| expect(recorder.phase).toBe("recording"); | ||
| }); | ||
|
|
||
| it("does not close the replacement microphone when an abandoned mixer finishes", async () => { | ||
| const pendingMixer = deferred<ReturnType<typeof mixer>>(); | ||
| const abandoned = mixer(); | ||
| const replacement = mixer(); | ||
| const firstMic = new Stream(); | ||
| const nextMic = new Stream(); | ||
| mocks.mic.mockResolvedValueOnce(firstMic).mockResolvedValueOnce(nextMic); | ||
| mocks.mixer | ||
| .mockReturnValueOnce(pendingMixer.promise) | ||
| .mockResolvedValueOnce(replacement); | ||
| let starting!: Promise<void>; | ||
| await act(async () => { | ||
| starting = recorder.start(); | ||
| }); | ||
| await act(async () => recorder.cancel()); | ||
| await act(async () => recorder.start()); | ||
| await act(async () => { | ||
| pendingMixer.resolve(abandoned); | ||
| await starting; | ||
| }); | ||
| expect(abandoned.close).toHaveBeenCalled(); | ||
| expect(firstMic.track.stop).toHaveBeenCalled(); | ||
| expect(nextMic.track.stop).not.toHaveBeenCalled(); | ||
| expect(replacement.close).not.toHaveBeenCalled(); | ||
| expect(recorder.phase).toBe("recording"); | ||
| }); | ||
|
|
||
| it("still finishes a current recording with the decoded waveform", async () => { | ||
| await act(async () => recorder.start()); | ||
| await act(async () => recorder.stop()); | ||
| expect(onFinish).toHaveBeenCalledTimes(1); | ||
| expect(onFinish).toHaveBeenCalledWith( | ||
| expect.objectContaining({ | ||
| mime: "audio/webm", | ||
| waveform: [0.25, 1], | ||
| blob: expect.objectContaining({ size: 5 }), | ||
| }), | ||
| ); | ||
| expect(recorder.phase).toBe("idle"); | ||
| }); | ||
|
|
||
| it("releases a microphone granted after startup was cancelled", async () => { | ||
| const pendingMic = deferred<Stream>(); | ||
| const stream = new Stream(); | ||
| mocks.mic.mockReturnValueOnce(pendingMic.promise); | ||
| let starting!: Promise<void>; | ||
| await act(async () => { | ||
| starting = recorder.start(); | ||
| }); | ||
| await act(async () => recorder.cancel()); | ||
| await act(async () => { | ||
| pendingMic.resolve(stream); | ||
| await starting; | ||
| }); | ||
| expect(stream.track.stop).toHaveBeenCalled(); | ||
| expect(mocks.mixer).not.toHaveBeenCalled(); | ||
| expect(onFinish).not.toHaveBeenCalled(); | ||
| expect(recorder.phase).toBe("idle"); | ||
| }); | ||
|
|
||
| it.each(["start", "restart"])( | ||
| "releases capture when recorder %s throws", | ||
| async (operation) => { | ||
| const stream = new Stream(); | ||
| const activeMixer = mixer(); | ||
| mocks.mic.mockResolvedValueOnce(stream); | ||
| mocks.mixer.mockResolvedValueOnce(activeMixer); | ||
| if (operation === "restart") await act(async () => recorder.start()); | ||
| Recorder.startError = new Error("Encoder unavailable"); | ||
| await act(async () => { | ||
| if (operation === "start") await recorder.start(); | ||
| else recorder.restart(); | ||
| }); | ||
| expect(recorder.phase).toBe("denied"); | ||
| expect(stream.track.stop).toHaveBeenCalled(); | ||
| expect(activeMixer.close).toHaveBeenCalled(); | ||
| expect(onFinish).not.toHaveBeenCalled(); | ||
| }, | ||
| ); | ||
|
|
||
| it("keeps a replacement take when the previous stop event arrives late", async () => { | ||
| await act(async () => recorder.start()); | ||
| Recorder.pendingStops = []; | ||
| let oldStop!: Promise<void>; | ||
| let newStart!: Promise<void>; | ||
| await act(async () => { | ||
| oldStop = recorder.stop(); | ||
| recorder.cancel(); | ||
| newStart = recorder.start(); | ||
| await newStart; | ||
| await oldStop; | ||
| }); | ||
| expect(recorder.phase).toBe("recording"); | ||
| const pending = Recorder.pendingStops; | ||
| Recorder.pendingStops = null; | ||
| await act(async () => { | ||
| for (const finish of pending ?? []) finish(); | ||
| }); | ||
| expect(recorder.phase).toBe("recording"); | ||
| await act(async () => recorder.stop()); | ||
| expect(onFinish).toHaveBeenCalledTimes(1); | ||
| expect(recorder.phase).toBe("idle"); | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.