@startsimpli/integrations 0.2.54 → 0.2.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,129 @@
1
+ // @vitest-environment jsdom
2
+ /**
3
+ * RED for bd startsim-lkvwd (epic startsim-ikxdz): the shared record button,
4
+ * the 24 MB recorder cap, and the Safari (audio/mp4) mime fallback.
5
+ */
6
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
7
+ import * as React from 'react';
8
+ import { afterEach, describe, expect, it, vi } from 'vitest';
9
+
10
+ import { VoiceNotesPage } from '../components/pages/VoiceNotesPage';
11
+ import { VoiceRecordButton, pickMimeType } from '../components/pages/VoiceRecordButton';
12
+ import type { VoiceNotesApi } from '../corpus/voice';
13
+
14
+ afterEach(() => { cleanup(); vi.unstubAllGlobals(); });
15
+
16
+ const MB = 1024 * 1024;
17
+
18
+ function api(over: Partial<VoiceNotesApi> = {}): VoiceNotesApi {
19
+ return {
20
+ submit: vi.fn(async () => ({ id: 'n2' })),
21
+ list: vi.fn(async () => []),
22
+ listFocuses: vi.fn(async () => []),
23
+ file: vi.fn(async () => undefined),
24
+ ...over,
25
+ };
26
+ }
27
+
28
+ /** A recorder you drive by hand: `emit(bytes)` is the browser handing over a timesliced chunk. */
29
+ function fakeRecorder(mimeType = 'audio/webm') {
30
+ const rec: any = {
31
+ mimeType,
32
+ state: 'inactive',
33
+ start: vi.fn(() => { rec.state = 'recording'; }),
34
+ emitted: 0,
35
+ // Like the browser: stop() flushes what is buffered, then fires onstop.
36
+ stop: vi.fn(() => {
37
+ if (!rec.emitted) rec.emit(3);
38
+ rec.state = 'inactive';
39
+ rec.onstop?.();
40
+ }),
41
+ emit: (bytes: number) => {
42
+ rec.emitted += bytes;
43
+ rec.ondataavailable?.({ data: new Blob([new Uint8Array(bytes)], { type: mimeType }) });
44
+ },
45
+ };
46
+ return rec;
47
+ }
48
+ const stream = { getTracks: () => [{ stop: vi.fn() }] } as unknown as MediaStream;
49
+ const devices = { getUserMedia: vi.fn(async () => stream) };
50
+
51
+ describe('VoiceRecordButton', () => {
52
+ it('records and submits through the api it is given', async () => {
53
+ const rec = fakeRecorder();
54
+ const submit = vi.fn(async () => ({ id: 'n2' }));
55
+ const onSaved = vi.fn();
56
+ render(<VoiceRecordButton api={{ submit }} onSaved={onSaved} mediaDevices={devices} recorderFactory={() => rec} />);
57
+ fireEvent.click(screen.getByText('Record a voice note'));
58
+ fireEvent.click(await screen.findByText(/^Stop/));
59
+ await waitFor(() => expect(submit).toHaveBeenCalledOnce());
60
+ await waitFor(() => expect(onSaved).toHaveBeenCalledWith({ id: 'n2' }));
61
+ });
62
+
63
+ it('the Home button and the Voice page submit through the same api.submit', async () => {
64
+ const shared = api();
65
+ for (const ui of [
66
+ <VoiceRecordButton key="home" api={shared} mediaDevices={devices} recorderFactory={() => fakeRecorder()} />,
67
+ <VoiceNotesPage key="page" api={shared} mediaDevices={devices} recorderFactory={() => fakeRecorder()} />,
68
+ ]) {
69
+ const rec = fakeRecorder();
70
+ const factory = () => rec;
71
+ const { unmount } = render(React.cloneElement(ui, { recorderFactory: factory } as never));
72
+ fireEvent.click(await screen.findByText('Record a voice note'));
73
+ fireEvent.click(await screen.findByText(/^Stop/));
74
+ await waitFor(() => expect((shared.submit as any).mock.calls.length).toBeGreaterThan(0));
75
+ unmount();
76
+ }
77
+ expect((shared.submit as any).mock.calls.length).toBe(2);
78
+ });
79
+
80
+ it('asks the recorder for timesliced chunks so the size can be watched', async () => {
81
+ const rec = fakeRecorder();
82
+ render(<VoiceRecordButton api={api()} mediaDevices={devices} recorderFactory={() => rec} />);
83
+ fireEvent.click(screen.getByText('Record a voice note'));
84
+ await screen.findByText(/^Stop/);
85
+ expect(typeof rec.start.mock.calls[0][0]).toBe('number');
86
+ });
87
+
88
+ it('stops by itself before the 24 MB server cap, says so, and still saves what it has', async () => {
89
+ const rec = fakeRecorder();
90
+ const submit = vi.fn(async () => ({ id: 'n2' }));
91
+ render(<VoiceRecordButton api={{ submit }} mediaDevices={devices} recorderFactory={() => rec} />);
92
+ fireEvent.click(screen.getByText('Record a voice note'));
93
+ await screen.findByText(/^Stop/);
94
+ rec.emit(12 * MB);
95
+ expect(rec.stop).not.toHaveBeenCalled();
96
+ rec.emit(11 * MB + 600 * 1024); // under the 24 MB cap, past the safety margin
97
+ await waitFor(() => expect(rec.stop).toHaveBeenCalledOnce());
98
+ await waitFor(() => expect(submit).toHaveBeenCalledOnce());
99
+ const [blob] = submit.mock.calls[0] as unknown as [Blob];
100
+ expect(blob.size).toBeLessThanOrEqual(24 * MB);
101
+ expect((await screen.findByRole('status')).textContent).toMatch(/size limit|too long|24 MB/i);
102
+ });
103
+ });
104
+
105
+ describe('recorder mime type (Safari records audio/mp4)', () => {
106
+ const candidates = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg;codecs=opus'];
107
+ for (const candidate of candidates) {
108
+ it(`falls back to ${candidate} when it is the only one supported`, () => {
109
+ expect(pickMimeType((t) => t === candidate)).toBe(candidate);
110
+ });
111
+ }
112
+ it('prefers webm/opus when everything is supported, and returns "" when nothing is', () => {
113
+ expect(pickMimeType(() => true)).toBe('audio/webm;codecs=opus');
114
+ expect(pickMimeType(() => false)).toBe('');
115
+ });
116
+
117
+ it('hands the Safari type to the recorder and uploads an audio/mp4 blob', async () => {
118
+ vi.stubGlobal('MediaRecorder', { isTypeSupported: (t: string) => t === 'audio/mp4' });
119
+ const rec = fakeRecorder('audio/mp4');
120
+ const factory = vi.fn((_stream: MediaStream, _mime: string) => rec as MediaRecorder);
121
+ const submit = vi.fn(async () => ({ id: 'n2' }));
122
+ render(<VoiceRecordButton api={{ submit }} mediaDevices={devices} recorderFactory={factory} />);
123
+ fireEvent.click(screen.getByText('Record a voice note'));
124
+ fireEvent.click(await screen.findByText(/^Stop/));
125
+ await waitFor(() => expect(submit).toHaveBeenCalledOnce());
126
+ expect(factory.mock.calls[0][1]).toBe('audio/mp4');
127
+ expect((submit.mock.calls[0] as unknown as [Blob])[0].type).toBe('audio/mp4');
128
+ });
129
+ });
@@ -0,0 +1,58 @@
1
+ /** RED for bd startsim-lkvwd: the browser client for /corpus/voice (upload, retry, delete, audio). */
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+
4
+ import { createVoiceApi } from '../corpus/voice';
5
+ import { createVoiceServerClient } from '../corpus/voice-manage';
6
+
7
+ afterEach(() => vi.unstubAllGlobals());
8
+
9
+ function client(responses: Array<Response>) {
10
+ const fetchMock = vi.fn(async () => responses.shift()!);
11
+ const server = createVoiceServerClient({ getToken: async () => 'tok', fetch: fetchMock as never });
12
+ return { server, fetchMock };
13
+ }
14
+ const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status });
15
+
16
+ describe('createVoiceServerClient', () => {
17
+ it('uploads multipart to /corpus/voice with the caller\'s bearer', async () => {
18
+ const { server, fetchMock } = client([json({ id: 'n1' }, 202)]);
19
+ expect(await server.upload(new Blob(['abc']), { durationMs: 1200 })).toEqual({ id: 'n1' });
20
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
21
+ expect(url).toBe('/corpus/voice');
22
+ expect(init.method).toBe('POST');
23
+ expect((init.headers as Record<string, string>).authorization).toBe('Bearer tok');
24
+ expect((init.body as FormData).get('durationMs')).toBe('1200');
25
+ });
26
+
27
+ it('retry POSTs /corpus/voice/<id>/retry and delete DELETEs /corpus/voice/<id>', async () => {
28
+ const { server, fetchMock } = client([json({ id: 'n1' }, 202), new Response(null, { status: 204 })]);
29
+ await server.retry('n1');
30
+ await server.remove('n1');
31
+ const calls = fetchMock.mock.calls as unknown as Array<[string, RequestInit]>;
32
+ expect([calls[0][0], calls[0][1].method]).toEqual(['/corpus/voice/n1/retry', 'POST']);
33
+ expect([calls[1][0], calls[1][1].method]).toEqual(['/corpus/voice/n1', 'DELETE']);
34
+ });
35
+
36
+ it('fetches the audio WITH the bearer (an <audio src> cannot) and returns an object URL', async () => {
37
+ vi.stubGlobal('URL', Object.assign(URL, { createObjectURL: vi.fn(() => 'blob:abc') }));
38
+ const { server, fetchMock } = client([new Response(new Uint8Array([1, 2, 3]), { headers: { 'content-type': 'audio/webm' } })]);
39
+ expect(await server.audioUrl('n1')).toBe('blob:abc');
40
+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
41
+ expect(url).toBe('/corpus/voice/n1/audio');
42
+ expect((init.headers as Record<string, string>).authorization).toBe('Bearer tok');
43
+ });
44
+
45
+ it('turns a server refusal into an Error carrying its detail', async () => {
46
+ const { server } = client([json({ detail: 'Not found.' }, 404)]);
47
+ await expect(server.audioUrl('n1')).rejects.toThrow('Not found.');
48
+ });
49
+
50
+ it('createVoiceApi exposes the server client as submit/retry/remove/audioUrl', async () => {
51
+ const { server } = client([]);
52
+ const voice = createVoiceApi({ http: { get: vi.fn() } as never, scope: { orgId: 'o' } as never, server });
53
+ expect(voice.submit).toBe(server.upload);
54
+ expect(voice.retry).toBe(server.retry);
55
+ expect(voice.remove).toBe(server.remove);
56
+ expect(voice.audioUrl).toBe(server.audioUrl);
57
+ });
58
+ });
@@ -164,7 +164,7 @@ describe('createVoiceTranscriber', () => {
164
164
  const out = await createVoiceTranscriber({ service: service as never }).transcribe({
165
165
  audio: new Uint8Array([1]), mimeType: 'audio/webm', focusTitles: ['Crochets', 'Raise'],
166
166
  });
167
- expect(out).toBe('hello');
167
+ expect(out).toMatchObject({ text: 'hello', provider: 'p', model: 'm' });
168
168
  expect(service.transcribe).toHaveBeenCalledWith(expect.objectContaining({ hints: ['Crochets', 'Raise'], mimeType: 'audio/webm' }));
169
169
  });
170
170
  });
@@ -62,3 +62,5 @@ export type { WorkItemSlot } from './pages/work-items';
62
62
 
63
63
  // Voice notes (bd startsim-f3wtn): record, transcribe, summarise, file under a focus.
64
64
  export * from './pages/VoiceNotesPage';
65
+ export { VoiceRecordButton, VOICE_MIME_CANDIDATES } from './pages/VoiceRecordButton';
66
+ export type { VoiceRecordButtonProps, VoiceRecordClassNames } from './pages/VoiceRecordButton';
@@ -17,6 +17,7 @@
17
17
  import * as React from 'react';
18
18
 
19
19
  import type { VoiceNote, VoiceNotesApi, VoiceFocus } from '../../corpus/voice';
20
+ import { VoiceRecordButton, formatDuration } from './VoiceRecordButton';
20
21
 
21
22
  type Slot = 'root' | 'section' | 'card' | 'button' | 'recording' | 'muted' | 'error' | 'select';
22
23
  export type VoiceNotesClassNames = Partial<Record<Slot, string>>;
@@ -32,17 +33,7 @@ const FALLBACK: Record<Slot, string> = {
32
33
  select: 'rounded-md border px-2 py-1 text-sm',
33
34
  };
34
35
 
35
- /** Safari records mp4, Chrome/Firefox webm/ogg — pick the first the browser can make. */
36
- const CANDIDATE_TYPES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg;codecs=opus'];
37
-
38
- export function pickMimeType(isSupported: (type: string) => boolean): string {
39
- return CANDIDATE_TYPES.find((type) => isSupported(type)) ?? '';
40
- }
41
-
42
- export function formatDuration(ms: number): string {
43
- const total = Math.max(0, Math.round(ms / 1000));
44
- return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
45
- }
36
+ export { formatDuration, pickMimeType } from './VoiceRecordButton';
46
37
 
47
38
  export interface VoiceNotesPageProps {
48
39
  api: VoiceNotesApi;
@@ -54,8 +45,6 @@ export interface VoiceNotesPageProps {
54
45
  recorderFactory?: (stream: MediaStream, mimeType: string) => MediaRecorder;
55
46
  }
56
47
 
57
- type Phase = 'idle' | 'recording' | 'saving';
58
-
59
48
  export function VoiceNotesPage({
60
49
  api, classNames, pollMs = 3000, mediaDevices, recorderFactory,
61
50
  }: VoiceNotesPageProps) {
@@ -63,15 +52,13 @@ export function VoiceNotesPage({
63
52
 
64
53
  const [notes, setNotes] = React.useState<VoiceNote[] | null>(null);
65
54
  const [focuses, setFocuses] = React.useState<VoiceFocus[]>([]);
66
- const [phase, setPhase] = React.useState<Phase>('idle');
67
- const [elapsed, setElapsed] = React.useState(0);
68
55
  const [error, setError] = React.useState<string | null>(null);
56
+ const [busy, setBusy] = React.useState<Set<string>>(new Set());
57
+ const [audio, setAudio] = React.useState<Record<string, string>>({});
69
58
 
70
59
  // The api may be rebuilt by the parent; the effects below must not re-fire.
71
60
  const apiRef = React.useRef(api);
72
61
  apiRef.current = api;
73
- const recorderRef = React.useRef<MediaRecorder | null>(null);
74
- const startedAt = React.useRef(0);
75
62
 
76
63
  const refresh = React.useCallback(async () => {
77
64
  try {
@@ -93,61 +80,31 @@ export function VoiceNotesPage({
93
80
  return () => clearTimeout(timer);
94
81
  }, [processing, notes, pollMs, refresh]);
95
82
 
96
- React.useEffect(() => {
97
- if (phase !== 'recording') return undefined;
98
- const tick = setInterval(() => setElapsed(Date.now() - startedAt.current), 250);
99
- return () => clearInterval(tick);
100
- }, [phase]);
101
-
102
- async function start() {
103
- setError(null);
83
+ async function act(note: VoiceNote, run: () => Promise<void>, failure: string) {
84
+ setBusy((current) => new Set(current).add(note.id));
104
85
  try {
105
- const devices = mediaDevices ?? navigator.mediaDevices;
106
- if (!devices?.getUserMedia) throw new Error('This browser cannot record audio.');
107
- const stream = await devices.getUserMedia({ audio: true });
108
- const mimeType = pickMimeType((t) => typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported(t));
109
- const recorder = recorderFactory
110
- ? recorderFactory(stream, mimeType)
111
- : new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
112
- const chunks: Blob[] = [];
113
- recorder.ondataavailable = (event) => { if (event.data.size) chunks.push(event.data); };
114
- recorder.onstop = () => {
115
- stream.getTracks().forEach((track) => track.stop());
116
- const durationMs = Date.now() - startedAt.current;
117
- const blob = new Blob(chunks, { type: recorder.mimeType || mimeType || 'audio/webm' });
118
- void save(blob, durationMs);
119
- };
120
- recorderRef.current = recorder;
121
- startedAt.current = Date.now();
122
- setElapsed(0);
123
- recorder.start();
124
- setPhase('recording');
86
+ await run();
125
87
  } catch (e) {
126
- setPhase('idle');
127
- setError(
128
- e instanceof Error && e.name === 'NotAllowedError'
129
- ? 'Microphone access was blocked. Allow it in the browser and try again.'
130
- : e instanceof Error ? e.message : 'Could not start recording.',
131
- );
88
+ setError(e instanceof Error ? e.message : failure);
89
+ } finally {
90
+ setBusy((current) => { const next = new Set(current); next.delete(note.id); return next; });
132
91
  }
133
92
  }
134
93
 
135
- function stop() {
136
- setPhase('saving');
137
- recorderRef.current?.stop();
138
- }
94
+ const retry = (note: VoiceNote) => act(note, async () => {
95
+ await apiRef.current.retry?.(note.id);
96
+ await refresh();
97
+ }, 'Could not retry that note.');
139
98
 
140
- async function save(blob: Blob, durationMs: number) {
141
- try {
142
- if (blob.size === 0) throw new Error('Nothing was recorded.');
143
- await apiRef.current.submit(blob, { durationMs });
144
- await refresh();
145
- } catch (e) {
146
- setError(e instanceof Error ? e.message : 'Saving the recording failed.');
147
- } finally {
148
- setPhase('idle');
149
- }
150
- }
99
+ const remove = (note: VoiceNote) => act(note, async () => {
100
+ await apiRef.current.remove?.(note.id);
101
+ setNotes((current) => current?.filter((n) => n.id !== note.id) ?? current);
102
+ }, 'Could not delete that note.');
103
+
104
+ const play = (note: VoiceNote) => act(note, async () => {
105
+ const url = await apiRef.current.audioUrl?.(note.id);
106
+ if (url) setAudio((current) => ({ ...current, [note.id]: url }));
107
+ }, 'Could not load the recording.');
151
108
 
152
109
  async function move(note: VoiceNote, focusId: string) {
153
110
  const next = focusId || null;
@@ -164,15 +121,14 @@ export function VoiceNotesPage({
164
121
  return (
165
122
  <div className={cx('root')}>
166
123
  <section className={cx('section')}>
167
- {phase === 'recording' ? (
168
- <button type="button" className={cx('recording')} onClick={stop}>
169
- Stop · {formatDuration(elapsed)}
170
- </button>
171
- ) : (
172
- <button type="button" className={cx('button')} onClick={() => void start()} disabled={phase === 'saving'}>
173
- {phase === 'saving' ? 'Saving…' : 'Record a voice note'}
174
- </button>
175
- )}
124
+ <VoiceRecordButton
125
+ api={api}
126
+ onSaved={refresh}
127
+ mediaDevices={mediaDevices}
128
+ recorderFactory={recorderFactory}
129
+ classNames={{ button: cx('button'), recording: cx('recording'), muted: cx('muted'), error: cx('error') }}
130
+ hint={null}
131
+ />
176
132
  <p className={cx('muted')}>
177
133
  Say what needs doing and for which project. It is transcribed, summarised and filed under
178
134
  the project it sounds like — change it below if that guess is wrong.
@@ -197,6 +153,23 @@ export function VoiceNotesPage({
197
153
  {note.status === 'failed' ? (
198
154
  <p role="alert" className={cx('error')}>Could not process this note{note.error ? `: ${note.error}` : '.'}</p>
199
155
  ) : null}
156
+ {note.status === 'failed' && (api.retry || api.remove) ? (
157
+ <p>
158
+ {api.retry ? (
159
+ <button type="button" className={cx('button')} disabled={busy.has(note.id)} onClick={() => void retry(note)}>Retry</button>
160
+ ) : null}{' '}
161
+ {api.remove ? (
162
+ <button type="button" className={cx('button')} disabled={busy.has(note.id)} onClick={() => void remove(note)}>Delete</button>
163
+ ) : null}
164
+ </p>
165
+ ) : null}
166
+ {note.status === 'ready' && note.audioRef && api.audioUrl ? (
167
+ audio[note.id] ? (
168
+ <audio controls autoPlay src={audio[note.id]} aria-label={`Recording of ${note.title}`} />
169
+ ) : (
170
+ <button type="button" className={cx('button')} disabled={busy.has(note.id)} onClick={() => void play(note)}>Play recording</button>
171
+ )
172
+ ) : null}
200
173
  {note.summary ? <p style={{ whiteSpace: 'pre-line' }}>{note.summary}</p> : null}
201
174
  {note.transcript ? (
202
175
  <details>
@@ -0,0 +1,162 @@
1
+ /**
2
+ * THE RECORD BUTTON (bd startsim-ikxdz): one composer, mounted on Tandem Home and
3
+ * on the Voice page, so a quick note and a note from the full page are the same
4
+ * code path — `api.submit`, nothing else.
5
+ *
6
+ * THE RECORDER WATCHES ITS OWN SIZE. The server refuses a recording over 24 MB
7
+ * (nginx allows 25). A long note must not be lost at the last second to a 413,
8
+ * so the recorder asks for timesliced chunks, counts them, and stops itself a
9
+ * safety margin short of the cap — then SAYS it did, and still saves what it has.
10
+ *
11
+ * MIME TYPE: Chrome/Firefox make webm/ogg, Safari makes mp4. The first type the
12
+ * browser can make wins; with none supported the browser's own default is used.
13
+ */
14
+ import * as React from 'react';
15
+
16
+ import { MAX_VOICE_BYTES } from '../../corpus/voice-manage';
17
+ import type { VoiceNotesApi } from '../../corpus/voice';
18
+
19
+ export type VoiceRecordSlot = 'root' | 'button' | 'recording' | 'muted' | 'error';
20
+ export type VoiceRecordClassNames = Partial<Record<VoiceRecordSlot, string>>;
21
+
22
+ const FALLBACK: Record<VoiceRecordSlot, string> = {
23
+ root: 'space-y-2',
24
+ button: 'rounded-md border px-4 py-2 text-sm font-medium',
25
+ recording: 'rounded-md border px-4 py-2 text-sm font-medium',
26
+ muted: 'text-sm opacity-70',
27
+ error: 'rounded-md border p-3 text-sm',
28
+ };
29
+
30
+ export const VOICE_MIME_CANDIDATES = ['audio/webm;codecs=opus', 'audio/webm', 'audio/mp4', 'audio/ogg;codecs=opus'];
31
+
32
+ export function pickMimeType(isSupported: (type: string) => boolean): string {
33
+ return VOICE_MIME_CANDIDATES.find((type) => isSupported(type)) ?? '';
34
+ }
35
+
36
+ export function formatDuration(ms: number): string {
37
+ const total = Math.max(0, Math.round(ms / 1000));
38
+ return `${Math.floor(total / 60)}:${String(total % 60).padStart(2, '0')}`;
39
+ }
40
+
41
+ /** Stop this far short of the server cap: chunks arrive on a timer, and the last one lands after stop(). */
42
+ const SIZE_MARGIN_BYTES = 512 * 1024;
43
+ const TIMESLICE_MS = 1000;
44
+
45
+ type Phase = 'idle' | 'recording' | 'saving';
46
+
47
+ export interface VoiceRecordButtonProps {
48
+ api: Pick<VoiceNotesApi, 'submit'>;
49
+ /** Called after the server has the recording (processing continues there). */
50
+ onSaved?: (saved: { id: string }) => void | Promise<void>;
51
+ classNames?: VoiceRecordClassNames;
52
+ /** Injectable for tests; defaults to the browser's. */
53
+ mediaDevices?: Pick<MediaDevices, 'getUserMedia'>;
54
+ recorderFactory?: (stream: MediaStream, mimeType: string) => MediaRecorder;
55
+ /** Shown under the button; pass `null` to hide. */
56
+ hint?: React.ReactNode;
57
+ children?: React.ReactNode;
58
+ }
59
+
60
+ export function VoiceRecordButton({
61
+ api, onSaved, classNames, mediaDevices, recorderFactory, hint, children,
62
+ }: VoiceRecordButtonProps) {
63
+ const cx = (slot: VoiceRecordSlot) => classNames?.[slot] ?? FALLBACK[slot];
64
+ const [phase, setPhase] = React.useState<Phase>('idle');
65
+ const [elapsed, setElapsed] = React.useState(0);
66
+ const [error, setError] = React.useState<string | null>(null);
67
+ const [notice, setNotice] = React.useState<string | null>(null);
68
+
69
+ const apiRef = React.useRef(api);
70
+ apiRef.current = api;
71
+ const onSavedRef = React.useRef(onSaved);
72
+ onSavedRef.current = onSaved;
73
+ const recorderRef = React.useRef<MediaRecorder | null>(null);
74
+ const startedAt = React.useRef(0);
75
+
76
+ React.useEffect(() => {
77
+ if (phase !== 'recording') return undefined;
78
+ const tick = setInterval(() => setElapsed(Date.now() - startedAt.current), 250);
79
+ return () => clearInterval(tick);
80
+ }, [phase]);
81
+
82
+ async function save(blob: Blob, durationMs: number) {
83
+ try {
84
+ if (blob.size === 0) throw new Error('Nothing was recorded.');
85
+ const saved = await apiRef.current.submit(blob, { durationMs });
86
+ await onSavedRef.current?.(saved);
87
+ } catch (e) {
88
+ setError(e instanceof Error ? e.message : 'Saving the recording failed.');
89
+ } finally {
90
+ setPhase('idle');
91
+ }
92
+ }
93
+
94
+ async function start() {
95
+ setError(null);
96
+ setNotice(null);
97
+ try {
98
+ const devices = mediaDevices ?? navigator.mediaDevices;
99
+ if (!devices?.getUserMedia) throw new Error('This browser cannot record audio.');
100
+ const stream = await devices.getUserMedia({ audio: true });
101
+ const mimeType = pickMimeType((t) => typeof MediaRecorder !== 'undefined' && MediaRecorder.isTypeSupported(t));
102
+ const recorder = recorderFactory
103
+ ? recorderFactory(stream, mimeType)
104
+ : new MediaRecorder(stream, mimeType ? { mimeType } : undefined);
105
+ const chunks: Blob[] = [];
106
+ let total = 0;
107
+ let capped = false;
108
+ recorder.ondataavailable = (event) => {
109
+ if (!event.data.size) return;
110
+ chunks.push(event.data);
111
+ total += event.data.size;
112
+ if (!capped && total >= MAX_VOICE_BYTES - SIZE_MARGIN_BYTES) {
113
+ capped = true;
114
+ setNotice('Stopped at the 24 MB size limit — saving what was recorded. Start a new note to keep going.');
115
+ setPhase('saving');
116
+ recorder.stop();
117
+ }
118
+ };
119
+ recorder.onstop = () => {
120
+ stream.getTracks().forEach((track) => track.stop());
121
+ const durationMs = Date.now() - startedAt.current;
122
+ const blob = new Blob(chunks, { type: recorder.mimeType || mimeType || 'audio/webm' });
123
+ void save(blob, durationMs);
124
+ };
125
+ recorderRef.current = recorder;
126
+ startedAt.current = Date.now();
127
+ setElapsed(0);
128
+ recorder.start(TIMESLICE_MS);
129
+ setPhase('recording');
130
+ } catch (e) {
131
+ setPhase('idle');
132
+ setError(
133
+ e instanceof Error && e.name === 'NotAllowedError'
134
+ ? 'Microphone access was blocked. Allow it in the browser and try again.'
135
+ : e instanceof Error ? e.message : 'Could not start recording.',
136
+ );
137
+ }
138
+ }
139
+
140
+ function stop() {
141
+ setPhase('saving');
142
+ recorderRef.current?.stop();
143
+ }
144
+
145
+ return (
146
+ <div className={cx('root')}>
147
+ {phase === 'recording' ? (
148
+ <button type="button" className={cx('recording')} onClick={stop}>
149
+ Stop · {formatDuration(elapsed)}
150
+ </button>
151
+ ) : (
152
+ <button type="button" className={cx('button')} onClick={() => void start()} disabled={phase === 'saving'}>
153
+ {phase === 'saving' ? 'Saving…' : 'Record a voice note'}
154
+ </button>
155
+ )}
156
+ {hint !== undefined ? hint : null}
157
+ {notice ? <p role="status" className={cx('muted')}>{notice}</p> : null}
158
+ {error ? <p role="alert" className={cx('error')}>{error}</p> : null}
159
+ {children}
160
+ </div>
161
+ );
162
+ }
@@ -218,6 +218,22 @@ export {
218
218
  voiceExternalId,
219
219
  voiceToEntity,
220
220
  } from './voice';
221
+ export {
222
+ MAX_VOICE_BYTES,
223
+ VoiceNoteConflict,
224
+ VoiceNoteNotFound,
225
+ createVoiceServerClient,
226
+ deleteVoiceNote,
227
+ retryVoiceNote,
228
+ voiceAudioResponse,
229
+ voiceErrorResponse,
230
+ } from './voice-manage';
231
+ export type {
232
+ ManagedHttp,
233
+ ManagedVoiceAudioStore,
234
+ RetriedVoiceNote,
235
+ VoiceServerClient,
236
+ } from './voice-manage';
221
237
  export type {
222
238
  FinishedVoiceNote,
223
239
  FocusChoice,