diff --git a/src/_storybook/views/recording/memorization/ui/MemorizationRecordingView.stories.tsx b/src/_storybook/views/recording/memorization/ui/MemorizationRecordingView.stories.tsx index 1fa8488a..47c2a591 100644 --- a/src/_storybook/views/recording/memorization/ui/MemorizationRecordingView.stories.tsx +++ b/src/_storybook/views/recording/memorization/ui/MemorizationRecordingView.stories.tsx @@ -35,7 +35,21 @@ const meta = { export default meta; type Story = StoryObj; -export const Ready: Story = {}; +export const Ready: Story = { + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await waitFor(() => + expect( + canvas.getByText( + "60초 안에 문단 녹음을 마쳐 주세요. 시간이 초과되면 녹음은 삭제되며 분석되지 않습니다.", + ), + ).toBeVisible(), + ); + await expect( + canvas.getByText("문단 전체를 분석하므로 결과가 나오기까지 시간이 걸릴 수 있습니다."), + ).toBeVisible(); + }, +}; export const Preview: Story = { play: async ({ canvasElement }) => { await userEvent.click(within(canvasElement).getByRole("button", { name: "단락 미리 보기" })); @@ -46,6 +60,11 @@ export const Preview: Story = { export const UserReady: Story = { args: { initialPhase: "user-ready" }, + play: async ({ canvasElement }) => { + const canvas = within(canvasElement); + await waitFor(() => expect(canvas.getByText("남은 시간 01:00")).toBeVisible()); + await expect(canvas.getByRole("button", { name: "녹음 시작" })).toBeEnabled(); + }, }; export const Recording: Story = { diff --git a/src/features/memorization-sessions/config/recording.ts b/src/features/memorization-sessions/config/recording.ts new file mode 100644 index 00000000..88d26701 --- /dev/null +++ b/src/features/memorization-sessions/config/recording.ts @@ -0,0 +1,6 @@ +export const MEMORIZATION_RECORDING_LIMIT_MS = 60_000; + +export const MEMORIZATION_RECORDING_NOTICE = [ + "60초 안에 문단 녹음을 마쳐 주세요. 시간이 초과되면 녹음은 삭제되며 분석되지 않습니다.", + "문단 전체를 분석하므로 결과가 나오기까지 시간이 걸릴 수 있습니다.", +] as const; diff --git a/src/features/session-recording/models/interface.ts b/src/features/session-recording/models/interface.ts index ed75ebe1..5a03642b 100644 --- a/src/features/session-recording/models/interface.ts +++ b/src/features/session-recording/models/interface.ts @@ -7,14 +7,16 @@ export type RecordingSessionErrorCode = AudioCaptureErrorCode | "unknown"; export interface UseRecordingSessionOptions { readonly audioCaptureOptions?: AudioCaptureOptions; readonly now?: () => number; + readonly maxDurationMs?: number; readonly recordEvent?: RecordOperationEvent; } export interface UseRecordingSessionResult { readonly state: RecordingSessionState; readonly minDurationMs: number; - readonly start: () => Promise; - readonly stop: () => Promise; + readonly start: () => Promise<"started" | "failed" | "canceled">; + readonly stop: () => Promise<"recorded" | "discarded" | "failed" | "canceled">; + readonly elapsedMs: number; readonly cancel: () => void; readonly retry: () => void; readonly fail: (errorCode: RecordingSessionErrorCode) => void; diff --git a/src/features/session-recording/models/reducer/recording/index.ts b/src/features/session-recording/models/reducer/recording/index.ts index 3bccd8ce..024a8e73 100644 --- a/src/features/session-recording/models/reducer/recording/index.ts +++ b/src/features/session-recording/models/reducer/recording/index.ts @@ -9,6 +9,12 @@ export function recordingSessionReducer( action: RecordingSessionAction, ): RecordingSessionState { switch (action.type) { + case "preparing": + return { status: "starting" }; + case "stopping": + return { status: "stopping" }; + case "timeout": + return { status: "discarded", reason: "timeout" }; case "start": return { status: "recording", startedAtMs: action.startedAtMs }; case "record": diff --git a/src/features/session-recording/models/reducer/recording/interface.ts b/src/features/session-recording/models/reducer/recording/interface.ts index c11ce3d5..f997872e 100644 --- a/src/features/session-recording/models/reducer/recording/interface.ts +++ b/src/features/session-recording/models/reducer/recording/interface.ts @@ -3,12 +3,17 @@ import type { RecordingSessionErrorCode } from "@/features/session-recording/mod export type RecordingSessionState = | { readonly status: "idle" } + | { readonly status: "starting" } + | { readonly status: "stopping" } | { readonly status: "recording"; readonly startedAtMs: number } | { readonly status: "recorded"; readonly audio: CapturedAudio } - | { readonly status: "discarded"; readonly reason: "too-short" } + | { readonly status: "discarded"; readonly reason: "too-short" | "timeout" } | { readonly status: "failed"; readonly errorCode: RecordingSessionErrorCode }; export type RecordingSessionAction = + | { readonly type: "preparing" } + | { readonly type: "stopping" } + | { readonly type: "timeout" } | { readonly type: "start"; readonly startedAtMs: number } | { readonly type: "record"; readonly audio: CapturedAudio } | { readonly type: "discard-too-short" } diff --git a/src/features/session-recording/services/hooks/__tests__/useRecordingSession.test.tsx b/src/features/session-recording/services/hooks/__tests__/useRecordingSession.test.tsx index ea09871e..358f1a58 100644 --- a/src/features/session-recording/services/hooks/__tests__/useRecordingSession.test.tsx +++ b/src/features/session-recording/services/hooks/__tests__/useRecordingSession.test.tsx @@ -71,7 +71,8 @@ describe("useRecordingSession", () => { }); expect(result.current.state).toEqual({ status: "idle" }); - expect(recorderStop).toHaveBeenCalledTimes(1); + expect(recorderStop).not.toHaveBeenCalled(); + expect(options.createRecorder).not.toHaveBeenCalled(); expect(trackStop).toHaveBeenCalledTimes(1); }); @@ -116,3 +117,157 @@ describe("useRecordingSession", () => { expect(events.events.map((event) => event.phase)).toEqual(["started", "failed"]); }); }); + +describe("recording deadline", () => { + const originalUuid = Object.getOwnPropertyDescriptor(crypto, "randomUUID"); + beforeAll(() => { + Object.defineProperty(crypto, "randomUUID", { configurable: true, value: randomUUID }); + }); + afterAll(() => { + if (originalUuid) Object.defineProperty(crypto, "randomUUID", originalUuid); + else Reflect.deleteProperty(crypto, "randomUUID"); + }); + + function setup(limit: number | null = 60_000) { + let now = 0; + const trackStop = jest.fn(); + const recorder = createRecorder(); + const stream = { getTracks: () => [{ stop: trackStop }] } as unknown as MediaStream; + const options = { ...createAudioOptions(stream, recorder), clock: { now: () => now } }; + const hook = renderHook(() => + useRecordingSession({ audioCaptureOptions: options, maxDurationMs: limit ?? undefined }), + ); + return { + ...hook, + recorder, + trackStop, + setNow: (value: number) => { + now = value; + }, + finish: () => { + recorder.ondataavailable?.({ data: new Blob(["audio"]) } as BlobEvent); + recorder.onstop?.(new Event("stop")); + }, + }; + } + + it("starts the deadline after microphone permission is granted", async () => { + const pending = deferred(); + let now = 0; + const recorder = createRecorder(); + const options: AudioCaptureOptions = { + getUserMedia: () => pending.promise, + createRecorder: () => recorder, + isTypeSupported: () => true, + clock: { now: () => now }, + }; + const { result } = renderHook(() => + useRecordingSession({ audioCaptureOptions: options, maxDurationMs: 60_000 }), + ); + let start!: ReturnType; + act(() => { + start = result.current.start(); + }); + expect(result.current.state.status).toBe("starting"); + now = 30_000; + await act(async () => { + pending.resolve({ getTracks: () => [{ stop: jest.fn() }] } as unknown as MediaStream); + await start; + }); + expect(result.current.state).toEqual({ status: "recording", startedAtMs: 30_000 }); + expect(result.current.elapsedMs).toBe(0); + act(() => result.current.cancel()); + }); + + it.each([60_000, 75_000])( + "discards at %i ms even if timer callbacks were suspended", + async (elapsed) => { + const h = setup(); + await act(async () => { + await h.result.current.start(); + }); + h.setNow(elapsed); + await act(async () => { + expect(await h.result.current.stop()).toBe("discarded"); + }); + expect(h.result.current.state).toEqual({ status: "discarded", reason: "timeout" }); + expect(h.result.current.recordedAudio).toBeNull(); + expect(h.trackStop).toHaveBeenCalledTimes(1); + }, + ); + + it("discards on return to the page without needing a stop click", async () => { + const h = setup(); + await act(async () => { + await h.result.current.start(); + }); + h.setNow(80_000); + act(() => { + document.dispatchEvent(new Event("visibilitychange")); + }); + expect(h.result.current.state).toEqual({ status: "discarded", reason: "timeout" }); + expect(h.trackStop).toHaveBeenCalledTimes(1); + }); + + it("keeps a timely stop valid while final data arrives after 60 seconds", async () => { + const h = setup(); + await act(async () => { + await h.result.current.start(); + }); + h.setNow(59_900); + let stop!: ReturnType; + act(() => { + stop = h.result.current.stop(); + }); + h.setNow(65_000); + act(() => { + document.dispatchEvent(new Event("visibilitychange")); + }); + await act(async () => { + h.finish(); + expect(await stop).toBe("recorded"); + }); + expect(h.result.current.recordedAudio?.durationMs).toBe(59_900); + }); + + it("ignores canceled stop completion after a new recording has started", async () => { + const h = setup(); + await act(async () => { + await h.result.current.start(); + }); + h.setNow(1000); + let stop!: ReturnType; + act(() => { + stop = h.result.current.stop(); + }); + const oldStop = h.recorder.onstop; + act(() => h.result.current.retry()); + await act(async () => { + await h.result.current.start(); + }); + await act(async () => { + oldStop?.(new Event("stop")); + expect(await stop).toBe("canceled"); + }); + expect(h.result.current.state.status).toBe("recording"); + expect(h.result.current.recordedAudio).toBeNull(); + act(() => h.result.current.cancel()); + }); + + it("does not impose the memorization deadline when no limit was supplied", async () => { + const h = setup(null); + await act(async () => { + await h.result.current.start(); + }); + h.setNow(90_000); + let stop!: ReturnType; + act(() => { + stop = h.result.current.stop(); + }); + await act(async () => { + h.finish(); + expect(await stop).toBe("recorded"); + }); + expect(h.result.current.recordedAudio?.durationMs).toBe(90_000); + }); +}); diff --git a/src/features/session-recording/services/hooks/useRecordingSession.ts b/src/features/session-recording/services/hooks/useRecordingSession.ts index 423ca38c..0aea816f 100644 --- a/src/features/session-recording/services/hooks/useRecordingSession.ts +++ b/src/features/session-recording/services/hooks/useRecordingSession.ts @@ -1,6 +1,6 @@ "use client"; -import { useCallback, useEffect, useMemo, useReducer, useRef } from "react"; +import { useCallback, useEffect, useMemo, useReducer, useRef, useState } from "react"; import { MIN_RECORDING_DURATION_MS } from "@/features/session-recording/config/const"; import { @@ -19,8 +19,6 @@ import type { UseRecordingSessionResult, } from "@/features/session-recording/models/interface"; -const defaultNow = () => performance.now(); - function getRecordingErrorCode(error: unknown): RecordingSessionErrorCode { return error instanceof AudioCaptureError ? error.code : "unknown"; } @@ -28,66 +26,102 @@ function getRecordingErrorCode(error: unknown): RecordingSessionErrorCode { export function useRecordingSession( options: UseRecordingSessionOptions = {}, ): UseRecordingSessionResult { - const now = options.now ?? defaultNow; const recordEvent = options.recordEvent ?? recordBrowserOperationEvent; const captureId = useRef(null); const recorderRef = useRef(null); - const activeStartTokenRef = useRef(null); + const activeAttempt = useRef(null); const [state, dispatch] = useReducer(recordingSessionReducer, { status: "idle" }); + const [elapsedMs, setElapsedMs] = useState(0); + const maxDurationMs = options.maxDurationMs; - const beginRecordingStart = useCallback(() => { - const token = Symbol("recording-start"); - activeStartTokenRef.current = token; - return token; - }, []); - const invalidateRecordingStart = useCallback(() => { - activeStartTokenRef.current = null; + const cancelCapture = useCallback(() => { + activeAttempt.current = null; + recorderRef.current?.cancel(); }, []); - const isCurrentRecordingStart = useCallback( - (token: symbol) => token === activeStartTokenRef.current, - [], - ); - const getRecorder = useCallback(() => { - recorderRef.current ??= new AudioCapture(options.audioCaptureOptions); - return recorderRef.current; - }, [options.audioCaptureOptions]); + useEffect(() => cancelCapture, [cancelCapture]); + + const expire = useCallback(() => { + const recorder = recorderRef.current; + if (!activeAttempt.current || recorder?.getStatus() !== "recording") return false; + const elapsed = recorder.getElapsedMs(); + setElapsedMs(elapsed); + if (maxDurationMs === undefined || elapsed < maxDurationMs) return false; + cancelCapture(); + dispatch({ type: "timeout" }); + emitOperationEvent(recordEvent, { + operation: "recording.timeout", + phase: "canceled", + operationId: crypto.randomUUID(), + resourceId: captureId.current ?? "unstarted", + }); + return true; + }, [cancelCapture, maxDurationMs, recordEvent]); useEffect(() => { + if (state.status !== "recording") return; + const timer = window.setInterval(expire, 250); + const deadline = + maxDurationMs === undefined + ? undefined + : window.setTimeout( + expire, + Math.max(0, maxDurationMs - (recorderRef.current?.getElapsedMs() ?? 0)), + ); + document.addEventListener("visibilitychange", expire); + window.addEventListener("pageshow", expire); return () => { - invalidateRecordingStart(); - recorderRef.current?.cancel(); + window.clearInterval(timer); + window.clearTimeout(deadline); + document.removeEventListener("visibilitychange", expire); + window.removeEventListener("pageshow", expire); }; - }, [invalidateRecordingStart]); + }, [expire, maxDurationMs, state.status]); const start = useCallback(async () => { + if (activeAttempt.current) return "canceled" as const; + const token = Symbol("recording-attempt"); + activeAttempt.current = token; const operationId = crypto.randomUUID(); captureId.current = operationId; const context = { operation: "recording.start", operationId, resourceId: operationId }; emitOperationEvent(recordEvent, { ...context, phase: "started" }); - const token = beginRecordingStart(); - const recorder = getRecorder(); - + const recorder = new AudioCapture({ + ...options.audioCaptureOptions, + ...(options.now ? { clock: { now: options.now } } : {}), + }); + recorderRef.current = recorder; + setElapsedMs(0); + dispatch({ type: "preparing" }); try { - dispatch(startRecording(now())); - await recorder.start(); - if (!isCurrentRecordingStart(token)) { - recorder.cancel(); + const startedAtMs = await recorder.start(); + if (activeAttempt.current !== token || startedAtMs === null) { emitOperationEvent(recordEvent, { ...context, phase: "canceled" }); - return; + return "canceled" as const; } + dispatch(startRecording(startedAtMs)); emitOperationEvent(recordEvent, { ...context, phase: "succeeded" }); + return "started" as const; } catch (error) { - if (isCurrentRecordingStart(token)) { - dispatch(failRecording(getRecordingErrorCode(error))); - emitOperationEvent(recordEvent, { ...context, phase: "failed" }); - } else { + if (activeAttempt.current !== token) { emitOperationEvent(recordEvent, { ...context, phase: "canceled" }); + return "canceled" as const; } + activeAttempt.current = null; + dispatch(failRecording(getRecordingErrorCode(error))); + emitOperationEvent(recordEvent, { ...context, phase: "failed" }); + return "failed" as const; } - }, [beginRecordingStart, getRecorder, isCurrentRecordingStart, now, recordEvent]); + }, [options.audioCaptureOptions, options.now, recordEvent]); const stop = useCallback(async () => { + const token = activeAttempt.current; + const recorder = recorderRef.current; + if (!token || recorder?.getStatus() !== "recording") return "canceled" as const; + if (expire()) return "discarded" as const; + // stop() synchronously freezes capture duration before awaiting the final chunk. + const pendingAudio = recorder.stop(maxDurationMs); + dispatch({ type: "stopping" }); const context = { operation: "recording.stop", operationId: crypto.randomUUID(), @@ -95,21 +129,36 @@ export function useRecordingSession( }; emitOperationEvent(recordEvent, { ...context, phase: "started" }); try { - const audio = await getRecorder().stop(); + const audio = await pendingAudio; + if (activeAttempt.current !== token) { + emitOperationEvent(recordEvent, { ...context, phase: "canceled" }); + return "canceled" as const; + } + activeAttempt.current = null; + const tooShort = audio.durationMs < MIN_RECORDING_DURATION_MS; dispatch(recordAudio(audio)); - emitOperationEvent(recordEvent, { - ...context, - phase: audio.durationMs >= MIN_RECORDING_DURATION_MS ? "succeeded" : "failed", - }); + emitOperationEvent(recordEvent, { ...context, phase: tooShort ? "failed" : "succeeded" }); + return tooShort ? ("discarded" as const) : ("recorded" as const); } catch (error) { + if (activeAttempt.current !== token) { + emitOperationEvent(recordEvent, { ...context, phase: "canceled" }); + return "canceled" as const; + } + activeAttempt.current = null; + if (error instanceof AudioCaptureError && error.code === "duration-limit-exceeded") { + dispatch({ type: "timeout" }); + emitOperationEvent(recordEvent, { ...context, phase: "canceled" }); + return "discarded" as const; + } dispatch(failRecording(getRecordingErrorCode(error))); emitOperationEvent(recordEvent, { ...context, phase: "failed" }); + return "failed" as const; } - }, [getRecorder, recordEvent]); + }, [expire, maxDurationMs, recordEvent]); const reset = useCallback(() => { - invalidateRecordingStart(); - recorderRef.current?.cancel(); + cancelCapture(); + setElapsedMs(0); dispatch(resetRecording()); if (captureId.current) { emitOperationEvent(recordEvent, { @@ -120,19 +169,23 @@ export function useRecordingSession( }); captureId.current = null; } - }, [invalidateRecordingStart, recordEvent]); + }, [cancelCapture, recordEvent]); return useMemo( () => ({ state, + elapsedMs, minDurationMs: MIN_RECORDING_DURATION_MS, start, stop, cancel: reset, retry: reset, - fail: (errorCode: RecordingSessionErrorCode) => dispatch(failRecording(errorCode)), + fail: (errorCode: RecordingSessionErrorCode) => { + cancelCapture(); + dispatch(failRecording(errorCode)); + }, recordedAudio: state.status === "recorded" ? state.audio : null, }), - [reset, start, state, stop], + [cancelCapture, elapsedMs, reset, start, state, stop], ); } diff --git a/src/shared/lib/audio/AudioCapture.ts b/src/shared/lib/audio/AudioCapture.ts index 0cf84931..cc036645 100644 --- a/src/shared/lib/audio/AudioCapture.ts +++ b/src/shared/lib/audio/AudioCapture.ts @@ -42,6 +42,8 @@ export class AudioCapture { private format: AudioFormat | null = null; private startedAtMs = 0; private chunks: Blob[] = []; + private attempt: symbol | null = null; + private startedAtWallMs = 0; constructor(options: AudioCaptureOptions = {}) { const BrowserMediaRecorder = typeof MediaRecorder === "undefined" ? null : MediaRecorder; @@ -67,7 +69,15 @@ export class AudioCapture { return this.status; } - async start(): Promise { + getElapsedMs(): number { + return Math.max( + 0, + this.clock.now() - this.startedAtMs, + this.clock === defaultClock ? Date.now() - this.startedAtWallMs : 0, + ); + } + + async start(): Promise { if (this.status !== "idle") { throw new AudioCaptureError( "recorder-start-failed", @@ -75,6 +85,8 @@ export class AudioCapture { ); } + const attempt = Symbol("capture"); + this.attempt = attempt; this.status = "starting"; const format = chooseSupportedAudioFormat(this.isTypeSupported); @@ -87,26 +99,34 @@ export class AudioCapture { } try { - this.stream = await this.getUserMedia({ audio: true }); + const stream = await this.getUserMedia({ audio: true }); + if (this.attempt !== attempt) { + stream.getTracks().forEach((track) => track.stop()); + return null; + } + this.stream = stream; this.format = format; this.chunks = []; - this.startedAtMs = this.clock.now(); this.recorder = this.createRecorder(this.stream, { mimeType: format.mimeType }); this.recorder.ondataavailable = (event) => { - if (event.data.size > 0) { + if (this.attempt === attempt && event.data.size > 0) { this.chunks.push(event.data); } }; this.recorder.start(); + this.startedAtMs = this.clock.now(); + this.startedAtWallMs = Date.now(); this.status = "recording"; + return this.startedAtMs; } catch (cause) { + if (this.attempt !== attempt) return null; this.stopStreamTracks(); this.reset(); throw mapAudioCaptureStartError(cause); } } - async stop(): Promise { + async stop(maxDurationMs?: number): Promise { if (this.status !== "recording" || !this.recorder || !this.format) { throw new AudioCaptureError( "recorder-stop-failed", @@ -117,11 +137,23 @@ export class AudioCapture { this.status = "stopping"; const recorder = this.recorder; const format = this.format; + const attempt = this.attempt; + const chunks = this.chunks; + const durationMs = this.getElapsedMs(); + if (maxDurationMs !== undefined && durationMs >= maxDurationMs) { + this.cancel(); + throw new AudioCaptureError( + "duration-limit-exceeded", + "Audio recording exceeded its duration limit.", + ); + } try { await this.stopRecorder(recorder); - const durationMs = this.clock.now() - this.startedAtMs; - const blob = new Blob(this.chunks, { type: format.mimeType }); + if (this.attempt !== attempt) { + throw new AudioCaptureError("recorder-stop-failed", "Audio recording was canceled."); + } + const blob = new Blob(chunks, { type: format.mimeType }); if (blob.size === 0) { throw new AudioCaptureError("empty-audio-data", "Audio recording did not produce data."); @@ -136,16 +168,21 @@ export class AudioCapture { } catch (cause) { throw mapAudioCaptureStopError(cause); } finally { - this.stopStreamTracks(); - this.reset(); + if (this.attempt === attempt) { + this.stopStreamTracks(); + this.reset(); + } } } cancel(): void { + this.attempt = null; try { if (this.recorder?.state !== "inactive") { this.recorder?.stop(); } + } catch { + // Cancellation still releases tracks when the browser recorder has already failed. } finally { this.stopStreamTracks(); this.reset(); @@ -194,11 +231,14 @@ export class AudioCapture { } private reset(): void { + this.attempt = null; + if (this.recorder) this.recorder.ondataavailable = null; this.status = "idle"; this.recorder = null; this.stream = null; this.format = null; this.startedAtMs = 0; + this.chunks.length = 0; this.chunks = []; } } diff --git a/src/shared/lib/audio/__tests__/AudioCapture.test.ts b/src/shared/lib/audio/__tests__/AudioCapture.test.ts index bae56472..8a612039 100644 --- a/src/shared/lib/audio/__tests__/AudioCapture.test.ts +++ b/src/shared/lib/audio/__tests__/AudioCapture.test.ts @@ -226,3 +226,103 @@ describe("AudioCapture", () => { capture.cancel(); }); }); + +describe("capture attempt boundaries", () => { + it("freezes duration at stop request even when the last chunk arrives after the deadline", async () => { + const { stream } = createStream(); + const recorder = new FakeAudioRecorder(); + recorder.stop.mockImplementation(() => { + recorder.state = "inactive"; + }); + let now = 0; + const capture = new AudioCapture({ + getUserMedia: createGetUserMedia(stream), + createRecorder: () => recorder, + isTypeSupported: () => true, + clock: { now: () => now }, + }); + await capture.start(); + now = 59_900; + const pending = capture.stop(60_000); + now = 61_000; + recorder.ondataavailable?.({ data: new Blob(["valid"]) } as BlobEvent); + recorder.onstop?.(new Event("stop")); + expect((await pending).durationMs).toBe(59_900); + }); + + it("rejects a stop exactly at the limit and releases the microphone", async () => { + const { stream, stopTrack } = createStream(); + const recorder = new FakeAudioRecorder(); + const capture = new AudioCapture({ + getUserMedia: createGetUserMedia(stream), + createRecorder: () => recorder, + isTypeSupported: () => true, + clock: createClock(0, 60_000), + }); + await capture.start(); + await expect(capture.stop(60_000)).rejects.toMatchObject({ code: "duration-limit-exceeded" }); + expect(stopTrack).toHaveBeenCalledTimes(1); + expect(capture.getStatus()).toBe("idle"); + }); + + it("ignores canceled recorder chunks and completion while a new attempt is recording", async () => { + const old = new FakeAudioRecorder(); + old.stop.mockImplementation(() => { + old.state = "inactive"; + }); + const next = new FakeAudioRecorder(); + const firstStream = createStream(); + const nextStream = createStream(); + let attempt = 0; + let now = 0; + const capture = new AudioCapture({ + getUserMedia: async () => (attempt === 0 ? firstStream.stream : nextStream.stream), + createRecorder: () => (attempt++ === 0 ? old : next), + isTypeSupported: () => true, + clock: { now: () => now }, + }); + await capture.start(); + const lateData = old.ondataavailable; + now = 1000; + const pending = capture.stop(); + capture.cancel(); + await capture.start(); + lateData?.({ data: new Blob(["stale"]) } as BlobEvent); + old.onstop?.(new Event("stop")); + await expect(pending).rejects.toMatchObject({ code: "recorder-stop-failed" }); + expect(capture.getStatus()).toBe("recording"); + expect(nextStream.stopTrack).not.toHaveBeenCalled(); + now = 2000; + const audio = await capture.stop(); + expect(audio.blob.size).toBe(new Blob(["audio-data"]).size); + expect(audio.durationMs).toBe(1000); + }); +}); + +it("releases a late permission result without replacing the next capture", async () => { + let grantOld!: (stream: MediaStream) => void; + const oldStream = createStream(); + const nextStream = createStream(); + const recorder = new FakeAudioRecorder(); + const getUserMedia = jest + .fn() + .mockImplementationOnce( + () => + new Promise((resolve) => { + grantOld = resolve; + }), + ) + .mockResolvedValueOnce(nextStream.stream); + const createRecorder = jest.fn(() => recorder); + const capture = new AudioCapture({ getUserMedia, createRecorder, isTypeSupported: () => true }); + const oldStart = capture.start(); + capture.cancel(); + await capture.start(); + grantOld(oldStream.stream); + expect(await oldStart).toBeNull(); + expect(oldStream.stopTrack).toHaveBeenCalledTimes(1); + expect(nextStream.stopTrack).not.toHaveBeenCalled(); + expect(createRecorder).toHaveBeenCalledTimes(1); + expect(capture.getStatus()).toBe("recording"); + capture.cancel(); +}); diff --git a/src/shared/lib/audio/errors.ts b/src/shared/lib/audio/errors.ts index db864e5e..9f2cf6e8 100644 --- a/src/shared/lib/audio/errors.ts +++ b/src/shared/lib/audio/errors.ts @@ -18,7 +18,8 @@ export type AudioCaptureErrorCode = /** Recorder stop, stop event handling, or recorder error handling failed. */ | "recorder-stop-failed" /** Stop completed, but no audio bytes were emitted. */ - | "empty-audio-data"; + | "empty-audio-data" + | "duration-limit-exceeded"; export interface AudioCaptureErrorOptions { readonly cause?: unknown; diff --git a/src/views/recording/models/hooks.ts b/src/views/recording/models/hooks.ts index 71c54a84..17c40a7f 100644 --- a/src/views/recording/models/hooks.ts +++ b/src/views/recording/models/hooks.ts @@ -13,6 +13,7 @@ export interface UsePartnerAudioPlaybackInput { export interface UseRecordingTurnInput { store: RecordingSessionBaseStore; demoDurationMs: number; + maxDurationMs?: number; totalSteps: number; nextPhase: RecordingPhase; saveRecording?: (audio: CapturedAudio) => Promise; diff --git a/src/views/recording/models/recordingSessionMessage.ts b/src/views/recording/models/recordingSessionMessage.ts index 976d42b4..68b02fcf 100644 --- a/src/views/recording/models/recordingSessionMessage.ts +++ b/src/views/recording/models/recordingSessionMessage.ts @@ -12,6 +12,7 @@ const RECORDING_ERROR_MESSAGES: Record = { "recorder-start-failed": "녹음을 시작하지 못했습니다. 다시 시도해주세요.", "recorder-stop-failed": "녹음을 종료하지 못했습니다. 다시 시도해주세요.", "empty-audio-data": "녹음된 음성이 없습니다. 다시 녹음해주세요.", + "duration-limit-exceeded": "녹음 제한시간을 초과했습니다. 다시 녹음해 주세요.", unknown: "녹음을 처리하지 못했습니다. 다시 시도해 주세요", }; @@ -22,6 +23,9 @@ export function getRecordingSessionHint( partnerPlaybackBlocked = false, ): string { if (saveFailed) return "저장하지 못했습니다. 다시 시도해주세요."; + if (recordingState.status === "discarded" && recordingState.reason === "timeout") { + return "녹음 제한시간 60초를 초과해 이번 녹음이 삭제되었습니다. 다시 녹음해 주세요."; + } if (recordingState.status === "discarded") return "녹음이 너무 짧습니다. 다시 녹음해 주세요"; if (recordingState.status === "failed") return RECORDING_ERROR_MESSAGES[recordingState.errorCode]; diff --git a/src/views/recording/models/ui.ts b/src/views/recording/models/ui.ts index 29126390..9d3fb9a6 100644 --- a/src/views/recording/models/ui.ts +++ b/src/views/recording/models/ui.ts @@ -28,6 +28,9 @@ export interface RecordingPanelProps { durationLabel: string; message: string; saving?: boolean; + busy?: boolean; + timedOut?: boolean; + notice?: readonly string[]; recordedAudio?: CapturedAudio | null; actions: { toggle: () => void; @@ -38,6 +41,8 @@ export interface RecordingPanelProps { export interface RecordingReadyPanelProps { content: RecordingSessionClientConfig["ready"]; onStart: () => void; + durationLabel?: string; + notice?: readonly string[]; } export interface RecordingSessionViewProps { pillar: RecordingPillar; diff --git a/src/views/recording/services/hooks/__tests__/useRecordingTurn.integration.test.tsx b/src/views/recording/services/hooks/__tests__/useRecordingTurn.integration.test.tsx new file mode 100644 index 00000000..4d8d4107 --- /dev/null +++ b/src/views/recording/services/hooks/__tests__/useRecordingTurn.integration.test.tsx @@ -0,0 +1,176 @@ +import { afterEach, beforeEach, describe, expect, it, jest } from "@jest/globals"; +import { act, renderHook } from "@testing-library/react"; +import { randomUUID } from "node:crypto"; +import { useStore } from "zustand"; +import { createMemorizationRecordingSessionStore } from "../../../models/stores/memorizationRecordingSessionStore"; +import { useRecordingTurn } from "../useRecordingTurn"; +import type { AudioCaptureRecorder, CapturedAudio } from "@/shared/lib/audio"; +import { MEMORIZATION_RECORDING_LIMIT_MS } from "@/features/memorization-sessions/config/recording"; + +class BrowserRecorder implements AudioCaptureRecorder { + static isTypeSupported = () => true; + state: RecordingState = "inactive"; + ondataavailable: ((event: BlobEvent) => void) | null = null; + onerror: ((event: ErrorEvent) => void) | null = null; + onstop: ((event: Event) => void) | null = null; + start() { + this.state = "recording"; + } + stop() { + this.state = "inactive"; + this.ondataavailable?.({ data: new Blob(["valid recording"]) } as BlobEvent); + this.onstop?.(new Event("stop")); + } +} + +const descriptors = { + media: Object.getOwnPropertyDescriptor(navigator, "mediaDevices"), + recorder: Object.getOwnPropertyDescriptor(globalThis, "MediaRecorder"), + uuid: Object.getOwnPropertyDescriptor(crypto, "randomUUID"), +}; +const stopTrack = jest.fn(); +const getUserMedia = jest.fn<() => Promise>(); + +beforeEach(() => { + jest.useFakeTimers(); + stopTrack.mockClear(); + getUserMedia + .mockReset() + .mockResolvedValue({ getTracks: () => [{ stop: stopTrack }] } as unknown as MediaStream); + Object.defineProperty(navigator, "mediaDevices", { configurable: true, value: { getUserMedia } }); + Object.defineProperty(globalThis, "MediaRecorder", { + configurable: true, + value: BrowserRecorder, + }); + Object.defineProperty(crypto, "randomUUID", { configurable: true, value: randomUUID }); +}); +afterEach(() => { + jest.useRealTimers(); + for (const [target, key, descriptor] of [ + [navigator, "mediaDevices", descriptors.media], + [globalThis, "MediaRecorder", descriptors.recorder], + [crypto, "randomUUID", descriptors.uuid], + ] as const) { + if (descriptor) Object.defineProperty(target, key, descriptor); + else Reflect.deleteProperty(target, key); + } +}); + +function setup(limit: number | undefined = MEMORIZATION_RECORDING_LIMIT_MS) { + const saveRecording = jest.fn<(audio: CapturedAudio) => Promise>().mockResolvedValue(); + const store = createMemorizationRecordingSessionStore({ + initialPhase: "user-ready", + activeStep: 1, + totalSteps: 2, + demoDurationMs: 1000, + }); + const hook = renderHook(() => + useRecordingTurn({ + store: useStore(store), + totalSteps: 2, + demoDurationMs: 1000, + nextPhase: "user-ready", + saveRecording, + maxDurationMs: limit, + }), + ); + return { ...hook, store, saveRecording }; +} + +async function toggle(h: ReturnType) { + await act(async () => { + await h.result.current.toggle(); + }); +} + +describe("문단 녹음 제한의 화면·저장 경계", () => { + it("권한 대기에는 01:00을 유지하고 시작 실패를 녹음 중으로 덮지 않는다", async () => { + let reject!: (error: Error) => void; + getUserMedia.mockImplementationOnce( + () => + new Promise((_resolve, fail) => { + reject = fail; + }), + ); + const h = setup(); + let pending!: Promise; + act(() => { + pending = h.result.current.toggle(); + }); + act(() => jest.advanceTimersByTime(30_000)); + expect(h.result.current.durationLabel).toBe("남은 시간 01:00"); + expect(h.store.getState().phase).toBe("user-ready"); + await act(async () => { + reject(new DOMException("denied", "NotAllowedError")); + await pending; + }); + expect(h.result.current.phase).toBe("failed"); + expect(h.store.getState().phase).toBe("user-ready"); + h.unmount(); + }); + + it("타이머 만료 시 녹음을 폐기하고 저장·다음 문단 진행을 막으며 다시 60초로 시작한다", async () => { + const h = setup(); + await toggle(h); + act(() => jest.advanceTimersByTime(250)); + expect(h.result.current.durationLabel).toBe("남은 시간 01:00"); + act(() => jest.advanceTimersByTime(59_750)); + expect(h.result.current.timedOut).toBe(true); + expect(h.result.current.durationLabel).toBe("남은 시간 00:00"); + expect(h.result.current.recordedAudio).toBeNull(); + expect(stopTrack).toHaveBeenCalledTimes(1); + await act(async () => { + await h.result.current.save(); + }); + expect(h.saveRecording).not.toHaveBeenCalled(); + expect(h.store.getState().currentStep).toBe(1); + await toggle(h); + expect(h.result.current.phase).toBe("recording"); + expect(h.result.current.durationLabel).toBe("남은 시간 01:00"); + h.unmount(); + }); + + it("저장된 첫 문단은 유지하고 두 번째 문단의 초과 시도만 폐기한다", async () => { + const h = setup(); + await toggle(h); + act(() => jest.advanceTimersByTime(1000)); + await toggle(h); + const first = h.result.current.recordedAudio; + await act(async () => { + await h.result.current.save(); + }); + expect(h.saveRecording).toHaveBeenCalledWith(first); + expect(h.store.getState().currentStep).toBe(2); + await toggle(h); + act(() => jest.advanceTimersByTime(60_000)); + await act(async () => { + await h.result.current.save(); + }); + expect(h.saveRecording).toHaveBeenCalledTimes(1); + expect(h.store.getState().currentStep).toBe(2); + expect(h.result.current.recordedAudio).toBeNull(); + h.unmount(); + }); + + it("시간 내 녹음은 대기·저장 실패 후에도 보존하고 저장만 재시도한다", async () => { + const h = setup(); + h.saveRecording.mockRejectedValueOnce(new Error("offline")); + await toggle(h); + act(() => jest.advanceTimersByTime(59_900)); + await toggle(h); + const audio = h.result.current.recordedAudio; + act(() => jest.advanceTimersByTime(120_000)); + await act(async () => { + await h.result.current.save(); + }); + expect(h.result.current.recordedAudio).toBe(audio); + expect(h.result.current.phase).toBe("recorded"); + expect(h.store.getState().currentStep).toBe(1); + await act(async () => { + await h.result.current.save(); + }); + expect(h.saveRecording).toHaveBeenNthCalledWith(2, audio); + expect(h.store.getState().currentStep).toBe(2); + h.unmount(); + }); +}); diff --git a/src/views/recording/services/hooks/useRecordingTurn.ts b/src/views/recording/services/hooks/useRecordingTurn.ts index b00ad21b..a215d369 100644 --- a/src/views/recording/services/hooks/useRecordingTurn.ts +++ b/src/views/recording/services/hooks/useRecordingTurn.ts @@ -15,47 +15,44 @@ export function useRecordingTurn({ totalSteps, nextPhase, saveRecording, + maxDurationMs, }: UseRecordingTurnInput) { const { phase: storedPhase, - elapsedMs, recordingStarted, recordingStopped, saveStarted, saveSucceeded, saveFailure, retryRecording, - setElapsedMs, } = store; - const recording = useRecordingSession(); + const recording = useRecordingSession({ maxDurationMs }); const { state: recordingState, + elapsedMs, recordedAudio: audio, start, stop, retry: resetRecording, } = recording; - const startedAtRef = React.useRef(null); const operationInProgress = React.useRef(false); const recorderFailed = recordingState.status === "failed" || recordingState.status === "discarded"; const phase: RecordingPhase = recorderFailed ? "failed" : storedPhase; - const durationLabel = formatRecordingDuration( - phase === "recording" ? elapsedMs : (audio?.durationMs ?? demoDurationMs), - ); - - React.useEffect(() => { - if (phase !== "recording") return; - const id = window.setInterval(() => { - setElapsedMs(Date.now() - (startedAtRef.current ?? Date.now())); - }, 250); - return () => window.clearInterval(id); - }, [phase, setElapsedMs]); + const timedOut = recordingState.status === "discarded" && recordingState.reason === "timeout"; + const busy = recordingState.status === "starting" || recordingState.status === "stopping"; + const showRemaining = maxDurationMs !== undefined && !audio; + const remainingMs = Math.max(0, (maxDurationMs ?? 0) - elapsedMs); + const remainingSeconds = timedOut ? 0 : Math.ceil(remainingMs / 1000); + const durationLabel = showRemaining + ? `남은 시간 ${formatRecordingDuration(remainingSeconds * 1000)}` + : formatRecordingDuration( + phase === "recording" ? elapsedMs : (audio?.durationMs ?? demoDurationMs), + ); const retry = React.useCallback(() => { if (operationInProgress.current) return; resetRecording(); - startedAtRef.current = null; retryRecording(); }, [resetRecording, retryRecording]); @@ -65,16 +62,13 @@ export function useRecordingTurn({ operationInProgress.current = true; try { if (phase === "recording") { - await stop(); - recordingStopped(); + if ((await stop()) === "recorded") recordingStopped(); return; } if (phase !== "user-ready" && phase !== "failed") return; if (phase === "failed") resetRecording(); - startedAtRef.current = Date.now(); - await start(); - recordingStarted(); + if ((await start()) === "started") recordingStarted(); } finally { operationInProgress.current = false; } @@ -88,7 +82,6 @@ export function useRecordingTurn({ if (!saveRecording) throw new RecordingRequestError("RECORDING_SERVER_NOT_READY"); await saveRecording(audio); resetRecording(); - startedAtRef.current = null; saveSucceeded(totalSteps, nextPhase); } catch (error) { saveFailure(); @@ -107,5 +100,15 @@ export function useRecordingTurn({ totalSteps, ]); - return { phase, durationLabel, recordingState, recordedAudio: audio, retry, toggle, save }; + return { + phase, + durationLabel, + recordingState, + recordedAudio: audio, + busy, + timedOut, + retry, + toggle, + save, + }; } diff --git a/src/views/recording/ui/common/RecordingPanel.tsx b/src/views/recording/ui/common/RecordingPanel.tsx index 6e5b7fac..1c71d660 100644 --- a/src/views/recording/ui/common/RecordingPanel.tsx +++ b/src/views/recording/ui/common/RecordingPanel.tsx @@ -17,6 +17,9 @@ export function RecordingPanel({ durationLabel, message, saving = false, + busy = false, + timedOut = false, + notice, recordedAudio, actions, }: RecordingPanelProps) { @@ -48,13 +51,23 @@ export function RecordingPanel({ recorded || phase === "completed" || saving || + busy || (content.kind === "prompt" && content.unavailable === true) } onClick={actions.toggle} />
{durationLabel} -

{message}

+

+ {busy + ? recording + ? "녹음을 마무리하고 있습니다." + : "마이크 권한을 확인하고 있습니다." + : message} +

{(phase === "user-ready" || phase === "partner-speaking") && content.kind === "partner" && content.canReplay ? ( @@ -68,6 +81,21 @@ export function RecordingPanel({ ) : null} + {timedOut ? ( +
+ + + 다시 녹음 + +
+ ) : null} + {notice ? ( +
+ {notice.map((line) => ( +

{line}

+ ))} +
+ ) : null} {recorded ? (
diff --git a/src/views/recording/ui/common/RecordingReadyPanel.tsx b/src/views/recording/ui/common/RecordingReadyPanel.tsx index 2b2fbed7..48c28426 100644 --- a/src/views/recording/ui/common/RecordingReadyPanel.tsx +++ b/src/views/recording/ui/common/RecordingReadyPanel.tsx @@ -4,9 +4,14 @@ import type { RecordingReadyPanelProps } from "@/views/recording/models/ui"; import { Play } from "lucide-react"; import { RecordingPreviewDialog } from "./RecordingPreviewDialog"; -import { GlassButton } from "@/views/recording/ui/common/RecordingControls"; +import { GlassButton, TimerPill } from "@/views/recording/ui/common/RecordingControls"; -export function RecordingReadyPanel({ content, onStart }: RecordingReadyPanelProps) { +export function RecordingReadyPanel({ + content, + onStart, + notice, + durationLabel, +}: RecordingReadyPanelProps) { const { label, title, description, meta } = content; return (
@@ -37,6 +42,14 @@ export function RecordingReadyPanel({ content, onStart }: RecordingReadyPanelPro {content.startLabel ?? "시작하기"}
+ {durationLabel ? {durationLabel} : null} + {notice ? ( +
+ {notice.map((line) => ( +

{line}

+ ))} +
+ ) : null} ); diff --git a/src/views/recording/ui/common/RecordingSessionView.tsx b/src/views/recording/ui/common/RecordingSessionView.tsx index 1dc7392c..db25c1bb 100644 --- a/src/views/recording/ui/common/RecordingSessionView.tsx +++ b/src/views/recording/ui/common/RecordingSessionView.tsx @@ -7,7 +7,7 @@ export function RecordingSessionView({ pillar, children }: RecordingSessionViewP return (
{children} diff --git a/src/views/recording/ui/common/__tests__/RecordingPanel.test.tsx b/src/views/recording/ui/common/__tests__/RecordingPanel.test.tsx index d21357b3..94a5e950 100644 --- a/src/views/recording/ui/common/__tests__/RecordingPanel.test.tsx +++ b/src/views/recording/ui/common/__tests__/RecordingPanel.test.tsx @@ -39,3 +39,38 @@ describe("녹음 패널", () => { expect(screen.getByRole("button", { name: "다시 듣기" })).toBeTruthy(); }); }); + +it("시간 초과는 한 번 알리고 저장 없이 키보드로 다시 녹음할 수 있다", async () => { + const toggle = jest.fn(); + const user = userEvent.setup(); + render( + , + ); + expect(screen.getByRole("alert").textContent).toContain("삭제"); + expect(screen.queryByRole("button", { name: "저장하기" })).toBeNull(); + screen.getByRole("button", { name: "다시 녹음" }).focus(); + await user.keyboard("{Enter}"); + expect(toggle).toHaveBeenCalledTimes(1); +}); + +it("권한 대기와 종료 처리 중에는 중복 녹음 버튼을 비활성화한다", () => { + render( + , + ); + expect(screen.getByRole("button", { name: "녹음 시작" }).hasAttribute("disabled")).toBe(true); + expect(screen.getByText("마이크 권한을 확인하고 있습니다.")).toBeTruthy(); +}); diff --git a/src/views/recording/ui/memorization/MemorizationRecordingClient.tsx b/src/views/recording/ui/memorization/MemorizationRecordingClient.tsx index a95a67ab..65b2aa95 100644 --- a/src/views/recording/ui/memorization/MemorizationRecordingClient.tsx +++ b/src/views/recording/ui/memorization/MemorizationRecordingClient.tsx @@ -1,6 +1,11 @@ "use client"; import type { MemorizationRecordingClientProps } from "@/views/recording/models/ui"; +import { + MEMORIZATION_RECORDING_LIMIT_MS, + MEMORIZATION_RECORDING_NOTICE, +} from "@/features/memorization-sessions/config/recording"; + import { getMemorizationPrompt } from "../../models/memorizationPrompt"; import * as React from "react"; import { useStore } from "zustand"; @@ -28,6 +33,7 @@ export function MemorizationRecordingClient({ totalSteps: config.initial.totalSteps, nextPhase: "user-ready", saveRecording, + maxDurationMs: MEMORIZATION_RECORDING_LIMIT_MS, }); const beginTurn = React.useCallback(() => { startTurn(config.initial.totalSteps, "user-ready"); @@ -44,7 +50,12 @@ export function MemorizationRecordingClient({ saving={session.saving} /> {turn.phase === "ready" ? ( - + ) : turn.phase === "completed" ? ( ) : ( @@ -58,6 +69,9 @@ export function MemorizationRecordingClient({ durationLabel={turn.durationLabel} message={getRecordingSessionHint(turn.phase, turn.recordingState, session.saveFailed)} saving={session.saving} + busy={turn.busy} + timedOut={turn.timedOut} + notice={MEMORIZATION_RECORDING_NOTICE} recordedAudio={turn.recordedAudio} actions={{ toggle: turn.toggle, retry: turn.retry, save: turn.save }} /> diff --git a/src/views/recording/ui/role-play/RolePlayRecordingClient.tsx b/src/views/recording/ui/role-play/RolePlayRecordingClient.tsx index c0c2e529..46ea7714 100644 --- a/src/views/recording/ui/role-play/RolePlayRecordingClient.tsx +++ b/src/views/recording/ui/role-play/RolePlayRecordingClient.tsx @@ -60,6 +60,7 @@ export function RolePlayRecordingClient(props: RolePlayRecordingClientProps) { session.partnerPlaybackBlocked, )} saving={session.saving} + busy={turn.busy} recordedAudio={turn.recordedAudio} actions={{ toggle: turn.toggle, retry: turn.retry, save: turn.save }} />