@startsimpli/integrations 0.2.79 → 0.2.81

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.
Files changed (30) hide show
  1. package/README.md +1 -1
  2. package/package.json +12 -2
  3. package/src/native/components/FoundryTabsShell.tsx +56 -8
  4. package/src/native/components/MoreTabList.tsx +35 -0
  5. package/src/native/components/__tests__/FoundryTabsShell.more.test.tsx +101 -0
  6. package/src/native/index.ts +2 -0
  7. package/src/native/recording/__tests__/deeplink.test.ts +92 -0
  8. package/src/native/recording/__tests__/diagnostics.test.ts +80 -0
  9. package/src/native/recording/__tests__/fakeForm.ts +10 -0
  10. package/src/native/recording/__tests__/flow.test.ts +47 -0
  11. package/src/native/recording/__tests__/levels.test.ts +38 -0
  12. package/src/native/recording/__tests__/notes.test.ts +74 -0
  13. package/src/native/recording/__tests__/permissions.test.ts +64 -0
  14. package/src/native/recording/__tests__/recorder.test.ts +233 -0
  15. package/src/native/recording/__tests__/recorderAudio.test.ts +153 -0
  16. package/src/native/recording/__tests__/recovery.test.ts +45 -0
  17. package/src/native/recording/__tests__/session.test.ts +120 -0
  18. package/src/native/recording/deeplink.ts +57 -0
  19. package/src/native/recording/diagnostics.ts +65 -0
  20. package/src/native/recording/index.ts +15 -0
  21. package/src/native/recording/levels.ts +32 -0
  22. package/src/native/recording/notes.ts +46 -0
  23. package/src/native/recording/permissions.ts +49 -0
  24. package/src/native/recording/recorder.ts +164 -0
  25. package/src/native/recording/recorderAudio.ts +154 -0
  26. package/src/native/recording/recovery.ts +40 -0
  27. package/src/native/recording/session.ts +65 -0
  28. package/src/native/recording/strings.ts +4 -0
  29. package/src/native/shell/__tests__/overflow.test.ts +31 -0
  30. package/src/native/shell/overflow.ts +23 -0
@@ -0,0 +1,74 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createNotes as realCreateNotes } from '../notes';
3
+ import { FakeForm } from './fakeForm';
4
+ import { toVoiceNote } from '../../../corpus';
5
+
6
+ const createNotes = (d: Parameters<typeof realCreateNotes>[0]) => realCreateNotes({ createForm: () => new FakeForm() as never, ...d });
7
+ const json = (body: unknown, status = 200) => ({ ok: status < 400, status, json: async () => body }) as Response;
8
+
9
+ function entity(id: number, data: Record<string, unknown>) {
10
+ return { id, entity_type: 'source_document', name: `n${id}`, data: { source: 'voice', ...data } };
11
+ }
12
+
13
+ describe('notes', () => {
14
+ it('posts multipart audio + durationMs + the client noteId to /corpus/voice', async () => {
15
+ const authorizedFetch = vi.fn().mockResolvedValue(json({ id: '9', noteId: 'abc' }, 202));
16
+ const notes = createNotes({ tandemUrl: 'http://tandem/', authorizedFetch });
17
+ await notes.upload({ id: 'abc12345', uri: 'file:///d/a.m4a', durationMs: 3100 });
18
+ const [url, init] = authorizedFetch.mock.calls[0];
19
+ expect(url).toBe('http://tandem/corpus/voice');
20
+ expect(init.method).toBe('POST');
21
+ const parts = (init.body as FormData & { getParts(): Array<{ fieldName: string; string?: string; uri?: string; type?: string; name?: string }> }).getParts();
22
+ const byName = Object.fromEntries(parts.map((p) => [p.fieldName, p]));
23
+ expect(byName.audio).toMatchObject({ uri: 'file:///d/a.m4a', type: 'audio/mp4', name: 'note.m4a' });
24
+ expect(byName.durationMs.string).toBe('3100');
25
+ expect(byName.noteId.string).toBe('abc12345');
26
+ });
27
+
28
+ it('does not set Content-Type itself (the boundary is fetch\'s to add)', async () => {
29
+ const authorizedFetch = vi.fn().mockResolvedValue(json({}, 202));
30
+ await createNotes({ tandemUrl: 'http://t', authorizedFetch }).upload({ id: 'abc12345', uri: 'file:///a.m4a', durationMs: 1 });
31
+ expect(JSON.stringify(authorizedFetch.mock.calls[0][1].headers ?? {}).toLowerCase()).not.toContain('content-type');
32
+ });
33
+
34
+ it.each([500, 413, 401, 503])('a %s response rejects so the queue keeps the job', async (status) => {
35
+ const authorizedFetch = vi.fn().mockResolvedValue(json({ detail: 'nope' }, status));
36
+ await expect(
37
+ createNotes({ tandemUrl: 'http://t', authorizedFetch }).upload({ id: 'abc12345', uri: 'file:///a.m4a', durationMs: 1 }),
38
+ ).rejects.toThrow();
39
+ });
40
+
41
+ it('a network error rejects', async () => {
42
+ const authorizedFetch = vi.fn().mockRejectedValue(new TypeError('Network request failed'));
43
+ await expect(
44
+ createNotes({ tandemUrl: 'http://t', authorizedFetch }).upload({ id: 'abc12345', uri: 'file:///a.m4a', durationMs: 1 }),
45
+ ).rejects.toThrow();
46
+ });
47
+
48
+ it('recent() lists the last 5 voice notes through the shared toVoiceNote (either key spelling)', async () => {
49
+ const rows = [
50
+ entity(1, { title: 'Snake', voiceStatus: 'ready', occurredAt: '2026-11-02T10:00:00Z' }),
51
+ entity(2, { voice_status: 'processing', occurred_at: '2026-11-02T09:00:00Z' }),
52
+ ];
53
+ const authorizedFetch = vi.fn(async (url: string) =>
54
+ url.includes('/relationships') ? json({ results: [] }) : json({ results: rows }));
55
+ const out = await createNotes({ tandemUrl: 'http://t', authorizedFetch }).recent();
56
+ expect(out).toEqual(rows.map((r) => toVoiceNote(r as never, null)));
57
+ expect(out.map((n) => n.status)).toEqual(['ready', 'processing']);
58
+ const first = String(authorizedFetch.mock.calls[0][0]);
59
+ expect(first).toContain('http://t/api/v1/entities');
60
+ expect(first).toContain('source=voice');
61
+ expect(first).toContain('order=recent');
62
+ expect(first).toContain('page_size=5');
63
+ });
64
+
65
+ it('with a filePart (expo/fetch cannot send RN {uri} parts) the audio is appended as that Blob named note.m4a', async () => {
66
+ const authorizedFetch = vi.fn().mockResolvedValue(json({}, 202));
67
+ const blob = { kind: 'blob' };
68
+ const filePart = vi.fn(() => blob as never);
69
+ await createNotes({ tandemUrl: 'http://t', authorizedFetch, filePart }).upload({ id: 'abc12345', uri: 'file:///d/a.m4a', durationMs: 5 });
70
+ expect(filePart).toHaveBeenCalledWith('file:///d/a.m4a');
71
+ const parts = (authorizedFetch.mock.calls[0][1].body as FakeForm).getParts() as Array<Record<string, unknown>>;
72
+ expect(parts.find((p) => p.fieldName === 'audio')).toMatchObject({ name: 'note.m4a', blob });
73
+ });
74
+ });
@@ -0,0 +1,64 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createPermissionFlow, type PermissionsApi } from '../permissions';
3
+
4
+ const resp = (status: string, canAskAgain = true) => ({ status, granted: status === 'granted', canAskAgain, expires: 'never' });
5
+
6
+ function setup(initial = resp('undetermined'), asked = resp('granted')) {
7
+ const calls: string[] = [];
8
+ let current = initial;
9
+ const perms: PermissionsApi = {
10
+ get: vi.fn(async () => { calls.push('get'); return current; }),
11
+ request: vi.fn(async () => { calls.push('request'); current = asked; return asked; }),
12
+ };
13
+ const openSettings = vi.fn().mockResolvedValue(undefined);
14
+ const log = vi.fn();
15
+ const flow = createPermissionFlow({ perms, openSettings, log });
16
+ return { flow, perms, openSettings, log, calls, setCurrent: (r: ReturnType<typeof resp>) => { current = r; } };
17
+ }
18
+
19
+ describe('permission flow', () => {
20
+ it('first tap: asks, and resolves granted only AFTER the answer', async () => {
21
+ const s = setup();
22
+ expect(await s.flow.ensure()).toBe('granted');
23
+ expect(s.calls).toEqual(['get', 'request']);
24
+ });
25
+
26
+ it('already granted: no prompt', async () => {
27
+ const s = setup(resp('granted'));
28
+ expect(await s.flow.ensure()).toBe('granted');
29
+ expect(s.perms.request).not.toHaveBeenCalled();
30
+ });
31
+
32
+ it('user says no: denied, and logged with the state', async () => {
33
+ const s = setup(resp('undetermined'), resp('denied', false));
34
+ expect(await s.flow.ensure()).toBe('denied');
35
+ expect(s.log).toHaveBeenCalledWith('permission', expect.objectContaining({ status: 'denied' }));
36
+ });
37
+
38
+ it('previously denied (cannot ask again): does not prompt, reports denied', async () => {
39
+ const s = setup(resp('denied', false));
40
+ expect(await s.flow.ensure()).toBe('denied');
41
+ expect(s.perms.request).not.toHaveBeenCalled();
42
+ });
43
+
44
+ it('allowed later in Settings: the next ensure() is granted, no restart', async () => {
45
+ const s = setup(resp('denied', false));
46
+ expect(await s.flow.ensure()).toBe('denied');
47
+ s.setCurrent(resp('granted'));
48
+ expect(await s.flow.ensure()).toBe('granted');
49
+ });
50
+
51
+ it('openSettings delegates', async () => {
52
+ const s = setup();
53
+ await s.flow.openSettings();
54
+ expect(s.openSettings).toHaveBeenCalled();
55
+ });
56
+
57
+ it('a permission call that never answers times out loudly instead of hanging', async () => {
58
+ const log = vi.fn();
59
+ const perms = { get: () => new Promise<never>(() => undefined), request: vi.fn() };
60
+ const flow = createPermissionFlow({ perms, openSettings: vi.fn(), log, timeoutMs: 20 });
61
+ await expect(flow.ensure()).rejects.toThrow(/timed out/i);
62
+ expect(log).toHaveBeenCalledWith('permission', expect.objectContaining({ stage: 'timeout' }));
63
+ });
64
+ });
@@ -0,0 +1,233 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createRecorder, type RecorderAudio } from '../recorder';
3
+
4
+ const FILE = { uri: 'file:///docs/n.m4a', durationMs: 4200 };
5
+
6
+ function setup(over: Partial<RecorderAudio> = {}, send = vi.fn().mockResolvedValue('sent'), extra: Record<string, unknown> = {}) {
7
+ const audio: RecorderAudio = {
8
+ start: vi.fn().mockResolvedValue(undefined),
9
+ stop: vi.fn().mockResolvedValue(FILE),
10
+ ...over,
11
+ };
12
+ let n = 0;
13
+ const recorder = createRecorder({ audio, send, newId: () => `note-${++n}`, ...extra });
14
+ return { audio, send, recorder };
15
+ }
16
+
17
+ describe('recorder state machine', () => {
18
+ it('starts idle', () => {
19
+ expect(setup().recorder.getState().phase).toBe('idle');
20
+ });
21
+
22
+ it('GO -> recording', async () => {
23
+ const { recorder, audio } = setup();
24
+ await recorder.go();
25
+ expect(recorder.getState().phase).toBe('recording');
26
+ expect(audio.start).toHaveBeenCalledTimes(1);
27
+ });
28
+
29
+ it('GO while recording is a no-op', async () => {
30
+ const { recorder, audio } = setup();
31
+ await recorder.go();
32
+ await recorder.go();
33
+ expect(audio.start).toHaveBeenCalledTimes(1);
34
+ expect(recorder.getState().phase).toBe('recording');
35
+ });
36
+
37
+ it('STOP -> uploading -> sent, handing the file and a client noteId to send', async () => {
38
+ const phases: string[] = [];
39
+ const { recorder, send } = setup();
40
+ recorder.subscribe((s) => phases.push(s.phase));
41
+ await recorder.go();
42
+ await recorder.stop();
43
+ expect(send).toHaveBeenCalledWith({ id: 'note-1', uri: FILE.uri, durationMs: FILE.durationMs });
44
+ expect(phases).toEqual(['recording', 'uploading', 'sent']);
45
+ expect(recorder.getState().phase).toBe('sent');
46
+ });
47
+
48
+ it('STOP with an offline upload ends queued, not lost', async () => {
49
+ const { recorder } = setup({}, vi.fn().mockResolvedValue('queued'));
50
+ await recorder.go();
51
+ await recorder.stop();
52
+ expect(recorder.getState().phase).toBe('queued');
53
+ });
54
+
55
+ it('STOP always yields a file: a throwing send still ends queued', async () => {
56
+ const { recorder } = setup({}, vi.fn().mockRejectedValue(new Error('disk full')));
57
+ await recorder.go();
58
+ const file = await recorder.stop();
59
+ expect(file).toMatchObject({ uri: FILE.uri });
60
+ expect(recorder.getState().phase).toBe('queued');
61
+ });
62
+
63
+ it('STOP when not recording does nothing', async () => {
64
+ const { recorder, audio, send } = setup();
65
+ expect(await recorder.stop()).toBeNull();
66
+ expect(audio.stop).not.toHaveBeenCalled();
67
+ expect(send).not.toHaveBeenCalled();
68
+ });
69
+
70
+ it('GO again after sent starts a NEW note id', async () => {
71
+ const { recorder, send } = setup();
72
+ await recorder.go();
73
+ await recorder.stop();
74
+ await recorder.go();
75
+ await recorder.stop();
76
+ expect(send.mock.calls.map((c) => c[0].id)).toEqual(['note-1', 'note-2']);
77
+ });
78
+
79
+ it('a denied microphone stays idle and says why', async () => {
80
+ const { recorder } = setup({ start: vi.fn().mockRejectedValue(new Error('denied')) });
81
+ await recorder.go();
82
+ expect(recorder.getState()).toMatchObject({ phase: 'idle', error: 'denied' });
83
+ });
84
+
85
+ it('GO is ignored while uploading', async () => {
86
+ let release!: (v: 'sent') => void;
87
+ const send = vi.fn().mockImplementation(() => new Promise((r) => { release = r; }));
88
+ const { recorder, audio } = setup({}, send);
89
+ await recorder.go();
90
+ const stopping = recorder.stop();
91
+ await Promise.resolve();
92
+ await recorder.go();
93
+ expect(audio.start).toHaveBeenCalledTimes(1);
94
+ release('sent');
95
+ await stopping;
96
+ });
97
+ });
98
+
99
+ describe('recorder: permission, diagnostics, interruptions, autostop', () => {
100
+ it('GO waits for permission; recording only starts after the grant', async () => {
101
+ const order: string[] = [];
102
+ const ensurePermission = vi.fn(async () => { order.push('permission'); return 'granted' as const; });
103
+ const { recorder } = setup({ start: vi.fn(async () => { order.push('start'); }) }, undefined, { ensurePermission });
104
+ await recorder.go();
105
+ expect(order).toEqual(['permission', 'start']);
106
+ });
107
+
108
+ it('denied permission: never starts, state says so (UI shows Open Settings)', async () => {
109
+ const { recorder, audio } = setup({}, undefined, { ensurePermission: async () => 'denied' as const });
110
+ await recorder.go();
111
+ expect(audio.start).not.toHaveBeenCalled();
112
+ expect(recorder.getState()).toMatchObject({ phase: 'idle', permission: 'denied' });
113
+ });
114
+
115
+ it('after the user allows it in Settings, the next GO records (no restart)', async () => {
116
+ let answer: 'denied' | 'granted' = 'denied';
117
+ const { recorder } = setup({}, undefined, { ensurePermission: async () => answer });
118
+ await recorder.go();
119
+ answer = 'granted';
120
+ await recorder.go();
121
+ expect(recorder.getState()).toMatchObject({ phase: 'recording' });
122
+ expect(recorder.getState().permission).not.toBe('denied');
123
+ });
124
+
125
+ it('GO tapped twice during the permission prompt starts once', async () => {
126
+ let grant!: (v: 'granted') => void;
127
+ const ensurePermission = () => new Promise<'granted'>((r) => { grant = r; });
128
+ const { recorder, audio } = setup({}, undefined, { ensurePermission });
129
+ const a = recorder.go();
130
+ const b = recorder.go();
131
+ grant('granted');
132
+ await Promise.all([a, b]);
133
+ expect(audio.start).toHaveBeenCalledTimes(1);
134
+ });
135
+
136
+ it('live level reaches the state while recording', async () => {
137
+ let onLevel!: (db: number) => void;
138
+ const { recorder } = setup({ start: vi.fn(async (o: { onLevel: (db: number) => void }) => { onLevel = o.onLevel; }) });
139
+ await recorder.go();
140
+ onLevel(-20);
141
+ expect(recorder.getState().levelDb).toBe(-20);
142
+ });
143
+
144
+ it('warns "no audio" when the peak is below the floor, and STILL uploads', async () => {
145
+ const stopped = { ...FILE, bytes: 5000, peakDb: -90, rmsDb: -95 };
146
+ const { recorder, send } = setup({ stop: vi.fn().mockResolvedValue(stopped) });
147
+ await recorder.go();
148
+ await recorder.stop();
149
+ expect(send).toHaveBeenCalledTimes(1);
150
+ expect(recorder.getState().warning).toBe('no-audio');
151
+ });
152
+
153
+ it('no warning for a normal recording', async () => {
154
+ const { recorder } = setup({ stop: vi.fn().mockResolvedValue({ ...FILE, bytes: 5000, peakDb: -12, rmsDb: -30 }) });
155
+ await recorder.go();
156
+ await recorder.stop();
157
+ expect(recorder.getState().warning).toBeUndefined();
158
+ });
159
+
160
+ it('logs the facts of every recording: permission, ids, bytes, measured vs wall-clock duration, levels', async () => {
161
+ const log = vi.fn();
162
+ let t = 1000;
163
+ const { recorder } = setup(
164
+ { stop: vi.fn().mockResolvedValue({ ...FILE, bytes: 7777, peakDb: -10, rmsDb: -25 }) },
165
+ undefined,
166
+ { diag: { log }, now: () => { const v = t; t += 4500; return v; }, ensurePermission: async () => 'granted' as const },
167
+ );
168
+ await recorder.go();
169
+ await recorder.stop();
170
+ expect(log).toHaveBeenCalledWith('record.start', expect.objectContaining({ id: 'note-1', permission: 'granted' }));
171
+ expect(log).toHaveBeenCalledWith('record.stop', expect.objectContaining({
172
+ id: 'note-1', uri: FILE.uri, bytes: 7777, durationMs: 4200, elapsedMs: 4500, peakDb: -10, rmsDb: -25,
173
+ }));
174
+ });
175
+
176
+ it('interrupt() while recording finalizes the partial file and queues it', async () => {
177
+ const { recorder, send } = setup();
178
+ await recorder.go();
179
+ await recorder.interrupt('interruption');
180
+ expect(send).toHaveBeenCalledWith({ id: 'note-1', uri: FILE.uri, durationMs: FILE.durationMs });
181
+ expect(recorder.getState().phase).toBe('sent');
182
+ });
183
+
184
+ it('interrupt() when not recording is a no-op', async () => {
185
+ const { recorder, send } = setup();
186
+ await recorder.interrupt('interruption');
187
+ expect(send).not.toHaveBeenCalled();
188
+ });
189
+
190
+ it('autostop: stops and uploads by itself after N seconds', async () => {
191
+ let fire!: () => void;
192
+ const schedule = vi.fn((fn: () => void) => { fire = fn; return () => undefined; });
193
+ const { recorder, send } = setup({}, undefined, { schedule });
194
+ await recorder.go({ autostopSeconds: 5 });
195
+ expect(schedule).toHaveBeenCalledWith(expect.any(Function), 5000);
196
+ expect(send).not.toHaveBeenCalled();
197
+ fire();
198
+ await new Promise((r) => setImmediate(r));
199
+ expect(send).toHaveBeenCalledTimes(1);
200
+ });
201
+
202
+ it('a manual STOP cancels the pending autostop', async () => {
203
+ const cancel = vi.fn();
204
+ const schedule = vi.fn(() => cancel);
205
+ const { recorder } = setup({}, undefined, { schedule });
206
+ await recorder.go({ autostopSeconds: 30 });
207
+ await recorder.stop();
208
+ expect(cancel).toHaveBeenCalled();
209
+ });
210
+
211
+ it('no autostop scheduled for a plain GO', async () => {
212
+ const schedule = vi.fn(() => () => undefined);
213
+ const { recorder } = setup({}, undefined, { schedule });
214
+ await recorder.go();
215
+ expect(schedule).not.toHaveBeenCalled();
216
+ });
217
+
218
+ it('a permission check that throws (hang/timeout) shows a plain error and logs it; GO works again after', async () => {
219
+ const log = vi.fn();
220
+ let fail = true;
221
+ const { recorder } = setup({}, undefined, {
222
+ diag: { log },
223
+ ensurePermission: async () => { if (fail) throw new Error('permission get timed out'); return 'granted' as const; },
224
+ });
225
+ await recorder.go();
226
+ expect(recorder.getState()).toMatchObject({ phase: 'idle' });
227
+ expect(recorder.getState().error).toMatch(/microphone/i);
228
+ expect(log).toHaveBeenCalledWith('record.error', expect.objectContaining({ stage: 'permission', error: 'permission get timed out' }));
229
+ fail = false;
230
+ await recorder.go();
231
+ expect(recorder.getState().phase).toBe('recording');
232
+ });
233
+ });
@@ -0,0 +1,153 @@
1
+ import { describe, expect, it, vi, type Mock } from 'vitest';
2
+ import { createRecorderAudio, type AudioDriver, type SessionInspector } from '../recorderAudio';
3
+
4
+ function setup(sizes: number[] = [0, 4000, 8000, 8000], sessionOver: Record<string, unknown> = {}) {
5
+ const order: string[] = [];
6
+ let status = { url: 'file:///docs/x.m4a', durationMillis: 2500, metering: -30 as number | undefined, isRecording: true };
7
+ const driver: AudioDriver = {
8
+ configureSession: vi.fn(async () => { order.push('configure'); }),
9
+ create: vi.fn((profile: string) => { order.push(`create:${profile}`); }),
10
+ prepare: vi.fn(async () => { order.push('prepare'); }),
11
+ record: vi.fn(() => { order.push('record'); }),
12
+ stop: vi.fn(async () => { order.push('stop'); }),
13
+ status: vi.fn(() => status),
14
+ };
15
+ const listeners: { interruption?: (e: { type: 'began' | 'ended' }) => void; route?: (e: { reason: string }) => void } = {};
16
+ const session: SessionInspector = {
17
+ info: vi.fn(async () => ({ category: 'playAndRecord', mode: 'default', options: ['allowBluetooth'], sampleRate: 48000, inputs: [{ type: 'MicrophoneBuiltIn', name: 'iPhone Microphone' }], ...sessionOver })),
18
+ onInterruption: (cb) => { listeners.interruption = cb; return () => undefined; },
19
+ onRouteChange: (cb) => { listeners.route = cb; return () => undefined; },
20
+ };
21
+ const sizeQueue = [...sizes];
22
+ const fs = { size: vi.fn(async () => { order.push('size'); return sizeQueue.length > 1 ? sizeQueue.shift()! : sizeQueue[0]; }) };
23
+ let tick: (() => void) | undefined;
24
+ const poll = vi.fn((fn: () => void) => { tick = fn; return () => { tick = undefined; }; });
25
+ const diag = { log: vi.fn() };
26
+ const onInterrupted = vi.fn();
27
+ const audio = createRecorderAudio({ driver, session, fs, poll, sleep: async () => undefined, diag, onInterrupted, stepTimeoutMs: 30 });
28
+ return { audio, driver, order, fs, diag, listeners, onInterrupted, tick: () => tick?.(), setStatus: (s: Partial<typeof status>) => { status = { ...status, ...s }; } };
29
+ }
30
+
31
+ describe('recorder audio adapter', () => {
32
+ it('pins the order: session configured+active -> recorder CREATED -> prepared -> record (the DevHQ failure)', async () => {
33
+ const s = setup();
34
+ await s.audio.start({ onLevel: vi.fn() });
35
+ expect(s.order).toEqual(['configure', 'create:normal', 'prepare', 'record']);
36
+ });
37
+
38
+ it('logs the audio session facts for every recording', async () => {
39
+ const s = setup();
40
+ await s.audio.start({ onLevel: vi.fn() });
41
+ expect(s.diag.log).toHaveBeenCalledWith('audio.session', expect.objectContaining({
42
+ category: 'playAndRecord', mode: 'default', sampleRate: 48000, route: 'MicrophoneBuiltIn',
43
+ }));
44
+ });
45
+
46
+ it('flags a session that is not record-capable', async () => {
47
+ const s = setup([8000], { category: 'playback' });
48
+ await s.audio.start({ onLevel: vi.fn() });
49
+ expect(s.diag.log).toHaveBeenCalledWith('audio.session.warning', expect.objectContaining({ category: 'playback' }));
50
+ });
51
+
52
+ it('feeds live metering to onLevel and tracks peak/RMS', async () => {
53
+ const s = setup();
54
+ const onLevel = vi.fn();
55
+ await s.audio.start({ onLevel });
56
+ s.setStatus({ metering: -42 }); s.tick();
57
+ s.setStatus({ metering: -12 }); s.tick();
58
+ expect(onLevel).toHaveBeenNthCalledWith(1, -42);
59
+ expect(onLevel).toHaveBeenNthCalledWith(2, -12);
60
+ const out = await s.audio.stop();
61
+ expect(out.peakDb).toBe(-12);
62
+ expect(out.rmsDb).toBeLessThan(-12);
63
+ });
64
+
65
+ it('stop awaits the recorder, then waits for the file size to settle (finalized) before returning', async () => {
66
+ const s = setup([0, 4000, 8000, 8000]);
67
+ await s.audio.start({ onLevel: vi.fn() });
68
+ const out = await s.audio.stop();
69
+ expect(s.order.indexOf('stop')).toBeLessThan(s.order.indexOf('size'));
70
+ expect(out).toMatchObject({ uri: 'file:///docs/x.m4a', bytes: 8000, durationMs: 2500 });
71
+ });
72
+
73
+ it('a file that never gets bytes comes back with bytes 0 (caller warns), not hung', async () => {
74
+ const s = setup([0]);
75
+ await s.audio.start({ onLevel: vi.fn() });
76
+ const out = await s.audio.stop();
77
+ expect(out.bytes).toBe(0);
78
+ });
79
+
80
+ it('an interruption while recording asks the recorder to finalize+queue', async () => {
81
+ const s = setup();
82
+ await s.audio.start({ onLevel: vi.fn() });
83
+ s.listeners.interruption!({ type: 'began' });
84
+ expect(s.onInterrupted).toHaveBeenCalledWith('interruption');
85
+ expect(s.diag.log).toHaveBeenCalledWith('audio.interruption', { type: 'began' });
86
+ });
87
+
88
+ it('a route change is logged; if the recorder stopped because of it, finalize+queue; otherwise keep going', async () => {
89
+ const s = setup();
90
+ await s.audio.start({ onLevel: vi.fn() });
91
+ s.listeners.route!({ reason: 'newDeviceAvailable' });
92
+ expect(s.onInterrupted).not.toHaveBeenCalled();
93
+ expect(s.diag.log).toHaveBeenCalledWith('audio.route', expect.objectContaining({ reason: 'newDeviceAvailable' }));
94
+ s.setStatus({ isRecording: false });
95
+ s.listeners.route!({ reason: 'oldDeviceUnavailable' });
96
+ expect(s.onInterrupted).toHaveBeenCalledWith('route-change');
97
+ });
98
+
99
+ it('ignores session events when not recording', async () => {
100
+ const s = setup();
101
+ await s.audio.start({ onLevel: vi.fn() });
102
+ await s.audio.stop();
103
+ s.listeners.interruption?.({ type: 'began' });
104
+ expect(s.onInterrupted).not.toHaveBeenCalled();
105
+ });
106
+
107
+ describe('silent start failures (AVAudioRecorder.prepareToRecord returning false)', () => {
108
+ it('a failed prepare is logged loudly with the session facts, then retried ONCE with the simplest settings', async () => {
109
+ const s = setup();
110
+ (s.driver.prepare as Mock).mockRejectedValueOnce(new Error('Failed to prepare recorder'));
111
+ await s.audio.start({ onLevel: vi.fn() });
112
+ expect(s.order).toEqual(['configure', 'create:normal', 'configure', 'create:simple', 'prepare', 'record']);
113
+ expect(s.diag.log).toHaveBeenCalledWith('audio.start-failed', expect.objectContaining({
114
+ profile: 'normal', error: 'Failed to prepare recorder', category: 'playAndRecord', mode: 'default',
115
+ }));
116
+ });
117
+
118
+ it('record() that does not actually start (silent no-op) counts as a failure and is retried', async () => {
119
+ const s = setup();
120
+ (s.driver.status as Mock)
121
+ .mockReturnValueOnce({ url: 'file:///docs/x.m4a', durationMillis: 0, isRecording: false })
122
+ .mockReturnValue({ url: 'file:///docs/x.m4a', durationMillis: 0, isRecording: true });
123
+ await s.audio.start({ onLevel: vi.fn() });
124
+ expect(s.order.filter((o) => o.startsWith('create'))).toEqual(['create:normal', 'create:simple']);
125
+ });
126
+
127
+ it('fails twice -> start rejects with a plain message (never a silent no-op), both attempts logged', async () => {
128
+ const s = setup();
129
+ (s.driver.prepare as Mock).mockRejectedValue(new Error('Failed to prepare recorder'));
130
+ await expect(s.audio.start({ onLevel: vi.fn() })).rejects.toThrow(/microphone/i);
131
+ expect(s.diag.log).toHaveBeenCalledWith('audio.start-failed', expect.objectContaining({ profile: 'normal' }));
132
+ expect(s.diag.log).toHaveBeenCalledWith('audio.start-failed', expect.objectContaining({ profile: 'simple', final: true }));
133
+ expect(s.driver.record).not.toHaveBeenCalled();
134
+ });
135
+
136
+ it('a file that stays 0 bytes is logged as an empty recording', async () => {
137
+ const s = setup([0]);
138
+ await s.audio.start({ onLevel: vi.fn() });
139
+ await s.audio.stop();
140
+ expect(s.diag.log).toHaveBeenCalledWith('audio.empty-file', expect.objectContaining({ uri: 'file:///docs/x.m4a' }));
141
+ });
142
+ });
143
+
144
+ describe('a start step that never answers (hang)', () => {
145
+ it.each(['configureSession', 'prepare'] as const)('a hung %s times out, is logged with the step name, and retried once', async (step) => {
146
+ const s = setup();
147
+ (s.driver[step] as Mock).mockImplementationOnce(() => new Promise(() => undefined));
148
+ await s.audio.start({ onLevel: vi.fn() });
149
+ expect(s.diag.log).toHaveBeenCalledWith('audio.start-failed', expect.objectContaining({ profile: 'normal', step, error: expect.stringMatching(/timed out/i) }));
150
+ expect(s.order.filter((o) => o.startsWith('create'))).toEqual(['create:normal', 'create:simple'].slice(step === 'configureSession' ? 1 : 0));
151
+ });
152
+ });
153
+ });
@@ -0,0 +1,45 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { recoverOrphans } from '../recovery';
3
+
4
+ describe('orphan recovery (app killed mid-recording)', () => {
5
+ const files = [
6
+ { uri: 'file:///docs/AAAA-1111-bbbb.m4a', bytes: 5000 },
7
+ { uri: 'file:///docs/empty.m4a', bytes: 0 },
8
+ { uri: 'file:///docs/upload-queue.json', bytes: 40 },
9
+ { uri: 'file:///docs/CCCC-2222-dddd.m4a', bytes: 9000 },
10
+ ];
11
+
12
+ it('queues every non-empty m4a with an id derived from its name, skips empties and other files', async () => {
13
+ const enqueue = vi.fn().mockResolvedValue('queued');
14
+ const log = vi.fn();
15
+ const out = await recoverOrphans({ list: async () => files, enqueue, log });
16
+ expect(enqueue.mock.calls.map((c) => c[0])).toEqual([
17
+ expect.objectContaining({ id: 'AAAA-1111-bbbb', uri: 'file:///docs/AAAA-1111-bbbb.m4a' }),
18
+ expect.objectContaining({ id: 'CCCC-2222-dddd', uri: 'file:///docs/CCCC-2222-dddd.m4a' }),
19
+ ]);
20
+ expect(out).toEqual({ recovered: 2, skipped: 1 });
21
+ expect(log).toHaveBeenCalledWith('orphan.recovered', expect.objectContaining({ id: 'AAAA-1111-bbbb', bytes: 5000 }));
22
+ expect(log).toHaveBeenCalledWith('orphan.skipped', expect.objectContaining({ bytes: 0 }));
23
+ });
24
+
25
+ it('ids that would be rejected by the server are made valid (>= 8 chars, safe charset)', async () => {
26
+ const enqueue = vi.fn().mockResolvedValue('queued');
27
+ await recoverOrphans({ list: async () => [{ uri: 'file:///docs/a b.m4a', bytes: 10 }], enqueue, log: vi.fn() });
28
+ expect(enqueue.mock.calls[0][0].id).toMatch(/^[A-Za-z0-9_-]{8,64}$/);
29
+ });
30
+
31
+ it('is stable: the same file always maps to the same id', async () => {
32
+ const ids: string[] = [];
33
+ const enqueue = vi.fn(async (j: { id: string }) => { ids.push(j.id); return 'queued' as const; });
34
+ const list = async () => [{ uri: 'file:///docs/x.m4a', bytes: 10 }];
35
+ await recoverOrphans({ list, enqueue, log: vi.fn() });
36
+ await recoverOrphans({ list, enqueue, log: vi.fn() });
37
+ expect(ids[0]).toBe(ids[1]);
38
+ });
39
+
40
+ it('excludes the file being recorded right now', async () => {
41
+ const enqueue = vi.fn().mockResolvedValue('queued');
42
+ await recoverOrphans({ list: async () => files, enqueue, log: vi.fn(), isActive: (uri) => uri.includes('AAAA') });
43
+ expect(enqueue).toHaveBeenCalledTimes(1);
44
+ });
45
+ });