Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,21 @@ const meta = {
export default meta;
type Story = StoryObj<typeof meta>;

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: "단락 미리 보기" }));
Expand All @@ -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 = {
Expand Down
6 changes: 6 additions & 0 deletions src/features/memorization-sessions/config/recording.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export const MEMORIZATION_RECORDING_LIMIT_MS = 60_000;

export const MEMORIZATION_RECORDING_NOTICE = [
"60초 안에 문단 녹음을 마쳐 주세요. 시간이 초과되면 녹음은 삭제되며 분석되지 않습니다.",
"문단 전체를 분석하므로 결과가 나오기까지 시간이 걸릴 수 있습니다.",
] as const;
6 changes: 4 additions & 2 deletions src/features/session-recording/models/interface.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>;
readonly stop: () => Promise<void>;
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;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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":
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
});

Expand Down Expand Up @@ -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<MediaStream>();
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<typeof result.current.start>;
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<typeof h.result.current.stop>;
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<typeof h.result.current.stop>;
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<typeof h.result.current.stop>;
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);
});
});
Loading
Loading