@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,120 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createSession, type SecretStore } from '../session';
3
+
4
+ function jwt(secondsFromNow = 3600) {
5
+ const exp = Math.floor(Date.now() / 1000) + secondsFromNow;
6
+ const enc = (o: object) => Buffer.from(JSON.stringify(o)).toString('base64');
7
+ return `${enc({ alg: 'HS256' })}.${enc({ exp, iat: exp - 3600, userId: '1' })}.sig`;
8
+ }
9
+ const ok = (body: unknown, status = 200) => ({ ok: status < 400, status, json: async () => body }) as Response;
10
+
11
+ function vault(): SecretStore & { dump: () => Record<string, string> } {
12
+ const data: Record<string, string> = {};
13
+ return {
14
+ getRefreshToken: async () => data.refresh ?? null,
15
+ setRefreshToken: async (t) => { data.refresh = t; },
16
+ clear: async () => { delete data.refresh; },
17
+ dump: () => data,
18
+ };
19
+ }
20
+
21
+ function setup(handler: (url: string, init: RequestInit) => Response) {
22
+ const fetchMock = vi.fn(async (url: string, init: RequestInit) => handler(String(url), init ?? {}));
23
+ const storage = vault();
24
+ const states: string[] = [];
25
+ const session = createSession({ centralUrl: 'http://central', storage, fetch: fetchMock as never });
26
+ session.subscribe((s) => states.push(s));
27
+ return { session, fetchMock, storage, states };
28
+ }
29
+
30
+ describe('session', () => {
31
+ it('signs in as app=tandem in token mode and stores ONLY the refresh token', async () => {
32
+ const { session, fetchMock, storage } = setup((url) =>
33
+ url.endsWith('/auth/token/') ? ok({ access: jwt(), refresh: 'R1', user: { id: '1', email: 'q@x.y' } }) : ok({}, 404));
34
+ await session.signIn('q@x.y', 'hunter2');
35
+ const [url, init] = fetchMock.mock.calls[0];
36
+ expect(url).toBe('http://central/api/v1/auth/token/');
37
+ expect((init.headers as Record<string, string>)['X-Auth-Mode']).toBe('token');
38
+ expect(JSON.parse(String(init.body))).toMatchObject({ email: 'q@x.y', app: 'tandem' });
39
+ expect(storage.dump()).toEqual({ refresh: 'R1' });
40
+ expect(JSON.stringify(storage.dump())).not.toContain('hunter2');
41
+ expect(session.getState()).toBe('signedIn');
42
+ });
43
+
44
+ it('a wrong password stays signed out', async () => {
45
+ const { session } = setup(() => ok({ detail: 'No active account' }, 401));
46
+ await expect(session.signIn('q@x.y', 'bad')).rejects.toThrow();
47
+ expect(session.getState()).toBe('signedOut');
48
+ });
49
+
50
+ it('restore() on launch uses the stored refresh token (no password) and signs in', async () => {
51
+ const { session, storage, fetchMock } = setup((url) =>
52
+ url.endsWith('/token/refresh/') ? ok({ access: jwt(), refresh: 'R2' }) : ok({}, 404));
53
+ await storage.setRefreshToken('R1');
54
+ await session.restore();
55
+ expect(JSON.parse(String(fetchMock.mock.calls[0][1].body))).toEqual({ refresh: 'R1' });
56
+ expect(session.getState()).toBe('signedIn');
57
+ expect(storage.dump()).toEqual({ refresh: 'R2' });
58
+ });
59
+
60
+ it('restore() with nothing stored is signedOut without any request', async () => {
61
+ const { session, fetchMock } = setup(() => ok({}));
62
+ await session.restore();
63
+ expect(session.getState()).toBe('signedOut');
64
+ expect(fetchMock).not.toHaveBeenCalled();
65
+ });
66
+
67
+ it('a 401 triggers ONE refresh then a retry', async () => {
68
+ let tokenUsed = '';
69
+ const { session, fetchMock } = setup((url, init) => {
70
+ if (url.endsWith('/auth/token/')) return ok({ access: 'OLD.' + jwt().split('.').slice(1).join('.'), refresh: 'R1', user: { id: '1', email: 'q@x.y' } });
71
+ if (url.endsWith('/token/refresh/')) return ok({ access: jwt(7200), refresh: 'R2' });
72
+ tokenUsed = (init.headers as Record<string, string>).Authorization;
73
+ return tokenUsed.includes('OLD.') ? ok({}, 401) : ok({ fine: true });
74
+ });
75
+ await session.signIn('q@x.y', 'pw');
76
+ const res = await session.authorizedFetch('http://tandem/x');
77
+ expect(res.status).toBe(200);
78
+ expect(fetchMock.mock.calls.filter(([u]) => String(u).endsWith('/token/refresh/'))).toHaveLength(1);
79
+ });
80
+
81
+ it('refresh failure -> signedOut (sign-in screen) and the error surfaces', async () => {
82
+ const { session, storage, states } = setup((url) => {
83
+ if (url.endsWith('/auth/token/')) return ok({ access: jwt(), refresh: 'R1', user: { id: '1', email: 'q@x.y' } });
84
+ if (url.endsWith('/token/refresh/')) return ok({ detail: 'expired' }, 401);
85
+ return ok({}, 401);
86
+ });
87
+ await session.signIn('q@x.y', 'pw');
88
+ await expect(session.authorizedFetch('http://tandem/x')).rejects.toThrow();
89
+ expect(session.getState()).toBe('signedOut');
90
+ expect(states[states.length - 1]).toBe('signedOut');
91
+ expect(storage.dump()).toEqual({});
92
+ });
93
+
94
+ describe('offline is not signed out', () => {
95
+ const offline = () => { throw new TypeError('Network request failed'); };
96
+
97
+ it('restore() with no network keeps the session (the refresh token is still valid)', async () => {
98
+ const { session, storage } = setup(offline);
99
+ await storage.setRefreshToken('R1');
100
+ await session.restore();
101
+ expect(session.getState()).toBe('signedIn');
102
+ expect(storage.dump()).toEqual({ refresh: 'R1' });
103
+ });
104
+
105
+ it('authorizedFetch with no network rejects but stays signedIn', async () => {
106
+ const { session, storage } = setup(offline);
107
+ await storage.setRefreshToken('R1');
108
+ await session.restore();
109
+ await expect(session.authorizedFetch('http://tandem/x')).rejects.toThrow();
110
+ expect(session.getState()).toBe('signedIn');
111
+ });
112
+
113
+ it('a refresh the server REJECTS still signs out', async () => {
114
+ const { session, storage } = setup(() => ok({ detail: 'expired' }, 401));
115
+ await storage.setRefreshToken('R1');
116
+ await session.restore();
117
+ expect(session.getState()).toBe('signedOut');
118
+ });
119
+ });
120
+ });
@@ -0,0 +1,57 @@
1
+ import type { GoOptions } from './recorder';
2
+
3
+ /**
4
+ * tandemgo://record start recording (manual STOP)
5
+ * tandemgo://record?autostop=N start, and stop+upload after N seconds (device test hook)
6
+ * Held until the session is ready; ignored while already recording.
7
+ */
8
+ export function createDeepLink(deps: {
9
+ getPhase: () => string;
10
+ go: (options: GoOptions) => Promise<void> | void;
11
+ log?: (event: string, fields?: Record<string, unknown>) => void;
12
+ /** The app's URL scheme (default 'tandemgo'). */
13
+ scheme?: string;
14
+ }) {
15
+ const log = deps.log ?? (() => undefined);
16
+ const scheme = deps.scheme ?? 'tandemgo';
17
+ let ready = false;
18
+ let pending: GoOptions | null = null;
19
+
20
+ const run = (options: GoOptions, url: string) => {
21
+ if (deps.getPhase() === 'recording') {
22
+ log('deeplink', { url, action: 'ignored-recording' });
23
+ return;
24
+ }
25
+ log('deeplink', { url, action: 'start', ...options });
26
+ void deps.go(options);
27
+ };
28
+
29
+ return {
30
+ handle(url: string) {
31
+ const match = new RegExp(`^${scheme}://record(?:\\?(.*))?$`).exec(url);
32
+ if (!match) {
33
+ log('deeplink', { url, action: 'ignored-url' });
34
+ return;
35
+ }
36
+ const seconds = Number(new URLSearchParams(match[1] ?? '').get('autostop'));
37
+ const options: GoOptions = Number.isFinite(seconds) && seconds > 0 ? { autostopSeconds: seconds } : {};
38
+ if (!ready) {
39
+ pending = options;
40
+ log('deeplink', { url, action: 'waiting-for-session' });
41
+ return;
42
+ }
43
+ run(options, url);
44
+ },
45
+ async sessionReady() {
46
+ ready = true;
47
+ if (pending) {
48
+ const options = pending;
49
+ pending = null;
50
+ run(options, `${scheme}://record`);
51
+ }
52
+ },
53
+ sessionLost() {
54
+ ready = false;
55
+ },
56
+ };
57
+ }
@@ -0,0 +1,65 @@
1
+ export interface DiagEntry {
2
+ t: number;
3
+ event: string;
4
+ [field: string]: unknown;
5
+ }
6
+
7
+ export interface Diagnostics {
8
+ log(event: string, fields?: Record<string, unknown>): void;
9
+ entries(): DiagEntry[];
10
+ subscribe(listener: () => void): () => void;
11
+ flush(): Promise<void>;
12
+ }
13
+
14
+ const SECRET = /password|token|authorization|secret/i;
15
+
16
+ /**
17
+ * Always-on structured log. Each entry is also printed as ONE console line
18
+ * `[tandemgo] {json}` so a device run can be read with log streaming.
19
+ */
20
+ export function createDiagnostics(options: {
21
+ sink?: (line: string) => void;
22
+ now?: () => number;
23
+ max?: number;
24
+ persist?: (json: string) => Promise<void>;
25
+ /** Reads the persisted log so earlier launches survive a relaunch (evidence for kill/relaunch tests). */
26
+ load?: () => Promise<string | null>;
27
+ /** The console prefix (default 'tandemgo'). */
28
+ tag?: string;
29
+ } = {}): Diagnostics {
30
+ const tag = options.tag ?? 'tandemgo';
31
+ const sink = options.sink ?? ((line: string) => console.log(line));
32
+ const now = options.now ?? Date.now;
33
+ const max = options.max ?? 500;
34
+ let list: DiagEntry[] = [];
35
+ const listeners = new Set<() => void>();
36
+ // Earlier launches' entries are merged in BEFORE the first write, so a relaunch never overwrites them.
37
+ let saving: Promise<void> = (options.load ? options.load() : Promise.resolve(null))
38
+ .then((json) => {
39
+ if (!json) return;
40
+ const previous = JSON.parse(json);
41
+ if (Array.isArray(previous)) list = [...previous, ...list].slice(-max);
42
+ })
43
+ .catch(() => undefined);
44
+
45
+ return {
46
+ log(event, fields = {}) {
47
+ const safe: Record<string, unknown> = {};
48
+ for (const [k, v] of Object.entries(fields)) safe[k] = SECRET.test(k) ? '[redacted]' : v;
49
+ const entry: DiagEntry = { t: now(), event, ...safe };
50
+ list = [...list, entry].slice(-max);
51
+ try { sink(`[${tag}] ${JSON.stringify(entry)}`); } catch { /* logging must never break recording */ }
52
+ if (options.persist) {
53
+ // Serialised INSIDE the queued write: by then the earlier launches' entries are merged in.
54
+ saving = saving.then(() => options.persist!(JSON.stringify(list))).catch(() => undefined);
55
+ }
56
+ listeners.forEach((l) => l());
57
+ },
58
+ entries: () => [...list],
59
+ subscribe(listener) {
60
+ listeners.add(listener);
61
+ return () => { listeners.delete(listener); };
62
+ },
63
+ flush: () => saving,
64
+ };
65
+ }
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The Tandem Go recording path, packaged (bd startsim-ij1lw.9). Pure logic: nothing here
3
+ * imports react-native or expo. The device bindings (expo-audio driver, file system,
4
+ * AVAudioSession module) stay in the app shell and are injected through the interfaces
5
+ * `AudioDriver`, `SessionInspector`, `PermissionsApi` and `RecordingFile`.
6
+ */
7
+ export * from './levels';
8
+ export * from './diagnostics';
9
+ export * from './permissions';
10
+ export * from './recorder';
11
+ export * from './recorderAudio';
12
+ export * from './recovery';
13
+ export * from './deeplink';
14
+ export * from './session';
15
+ export * from './notes';
@@ -0,0 +1,32 @@
1
+ /** Peak below this (dBFS) over a whole recording means the mic heard nothing. */
2
+ export const NO_AUDIO_FLOOR_DB = -45;
3
+ const SILENCE_DB = -160;
4
+
5
+ export interface LevelSummary {
6
+ peakDb: number;
7
+ rmsDb: number;
8
+ samples: number;
9
+ }
10
+
11
+ export function createLevelTracker() {
12
+ let peak = SILENCE_DB;
13
+ let power = 0;
14
+ let n = 0;
15
+ return {
16
+ push(db: number) {
17
+ peak = Math.max(peak, db);
18
+ power += 10 ** (db / 10);
19
+ n += 1;
20
+ },
21
+ summary(): LevelSummary {
22
+ return { peakDb: peak, rmsDb: n ? 10 * Math.log10(power / n) : SILENCE_DB, samples: n };
23
+ },
24
+ };
25
+ }
26
+
27
+ export const isSilent = (s: Pick<LevelSummary, 'peakDb' | 'samples'>) => s.samples === 0 || s.peakDb < NO_AUDIO_FLOOR_DB;
28
+
29
+ /** dBFS -> 0..1 for the on-screen meter (-60 dB and below is empty). */
30
+ export function meterFraction(db: number): number {
31
+ return Math.min(1, Math.max(0, (db + 60) / 60));
32
+ }
@@ -0,0 +1,46 @@
1
+ import { createVoiceApi, type CorpusHttp, type CorpusScope } from '../../corpus';
2
+
3
+ export interface NoteFile {
4
+ id: string;
5
+ uri: string;
6
+ durationMs: number;
7
+ }
8
+
9
+ type AuthorizedFetch = (url: string, init?: RequestInit) => Promise<Response>;
10
+
11
+ /** Send recordings to Tandem and read the latest back; the note logic is the shared corpus voice api. */
12
+ export function createNotes(deps: { tandemUrl: string; authorizedFetch: AuthorizedFetch; limit?: number; createForm?: () => FormData; filePart?: (uri: string) => Blob }) {
13
+ const base = deps.tandemUrl.replace(/\/+$/, '');
14
+
15
+ const http: CorpusHttp = {
16
+ async get<T>(path: string, options?: { params?: Record<string, unknown> }) {
17
+ const query = new URLSearchParams();
18
+ for (const [k, v] of Object.entries(options?.params ?? {})) if (v !== undefined) query.set(k, String(v));
19
+ const qs = query.toString();
20
+ const res = await deps.authorizedFetch(`${base}/${path}${qs ? `?${qs}` : ''}`, { method: 'GET' });
21
+ if (!res.ok) throw Object.assign(new Error(`GET ${path} failed (${res.status})`), { status: res.status });
22
+ return (await res.json()) as T;
23
+ },
24
+ };
25
+
26
+ const voice = createVoiceApi({
27
+ http,
28
+ scope: {} as CorpusScope,
29
+ limit: deps.limit ?? 5,
30
+ upload: async () => { throw new Error('use notes.upload'); },
31
+ });
32
+
33
+ return {
34
+ /** POST /corpus/voice. The client noteId makes a retry land on the same note. Rejects on any non-2xx. */
35
+ async upload(file: NoteFile): Promise<void> {
36
+ const body = (deps.createForm ?? (() => new FormData()))();
37
+ if (deps.filePart) body.append('audio', deps.filePart(file.uri), 'note.m4a');
38
+ else body.append('audio', { uri: file.uri, name: 'note.m4a', type: 'audio/mp4' } as unknown as Blob);
39
+ body.append('durationMs', String(file.durationMs));
40
+ body.append('noteId', file.id);
41
+ const res = await deps.authorizedFetch(`${base}/corpus/voice`, { method: 'POST', body });
42
+ if (!res.ok) throw Object.assign(new Error(`Upload failed (${res.status})`), { status: res.status });
43
+ },
44
+ recent: () => voice.list(),
45
+ };
46
+ }
@@ -0,0 +1,49 @@
1
+ export interface PermissionResult {
2
+ status: string;
3
+ granted: boolean;
4
+ canAskAgain: boolean;
5
+ }
6
+
7
+ export interface PermissionsApi {
8
+ get(): Promise<PermissionResult>;
9
+ request(): Promise<PermissionResult>;
10
+ }
11
+
12
+ export type Permission = 'granted' | 'denied';
13
+
14
+ /**
15
+ * Microphone permission. ensure() resolves only after the user has answered, so
16
+ * recording can never start before the grant (the empty-file race).
17
+ */
18
+ export function createPermissionFlow(deps: {
19
+ perms: PermissionsApi;
20
+ openSettings: () => Promise<void>;
21
+ log?: (event: string, fields?: Record<string, unknown>) => void;
22
+ /** A native permission call that has not answered by then is a failure, not a wait (default 10 s; the prompt itself is exempt). */
23
+ timeoutMs?: number;
24
+ }) {
25
+ const log = deps.log ?? (() => undefined);
26
+ const limit = <T>(name: string, work: Promise<T>): Promise<T> => {
27
+ const ms = deps.timeoutMs ?? 10000;
28
+ let timer: ReturnType<typeof setTimeout>;
29
+ const timeout = new Promise<never>((_, reject) => {
30
+ timer = setTimeout(() => {
31
+ log('permission', { stage: 'timeout', call: name, ms });
32
+ reject(new Error(`permission ${name} timed out after ${ms} ms`));
33
+ }, ms);
34
+ });
35
+ return Promise.race([work, timeout]).finally(() => clearTimeout(timer));
36
+ };
37
+ return {
38
+ async ensure(): Promise<Permission> {
39
+ const before = await limit('get', deps.perms.get());
40
+ log('permission', { stage: 'check', status: before.status, canAskAgain: before.canAskAgain });
41
+ if (before.granted) return 'granted';
42
+ if (before.status === 'denied' && !before.canAskAgain) return 'denied';
43
+ const after = await deps.perms.request();
44
+ log('permission', { stage: 'prompt', status: after.status, canAskAgain: after.canAskAgain });
45
+ return after.granted ? 'granted' : 'denied';
46
+ },
47
+ openSettings: () => deps.openSettings(),
48
+ };
49
+ }
@@ -0,0 +1,164 @@
1
+ import type { Permission } from './permissions';
2
+ import { isSilent } from './levels';
3
+ import { STRINGS } from './strings';
4
+
5
+ export interface StoppedRecording {
6
+ uri: string;
7
+ durationMs: number;
8
+ bytes?: number;
9
+ peakDb?: number;
10
+ rmsDb?: number;
11
+ }
12
+
13
+ export interface RecorderAudio {
14
+ start(handlers: { onLevel: (db: number) => void }): Promise<void>;
15
+ /** Resolves only when the file is finalized on disk. */
16
+ stop(): Promise<StoppedRecording>;
17
+ }
18
+
19
+ export type Phase = 'idle' | 'recording' | 'uploading' | 'sent' | 'queued';
20
+
21
+ export interface RecorderState {
22
+ phase: Phase;
23
+ noteId?: string;
24
+ error?: string;
25
+ permission?: Permission;
26
+ /** Set after STOP when the mic heard nothing. The note is still uploaded. */
27
+ warning?: 'no-audio';
28
+ levelDb?: number;
29
+ }
30
+
31
+ export interface GoOptions {
32
+ autostopSeconds?: number;
33
+ }
34
+
35
+ export type SendFile = {
36
+ id: string;
37
+ uri: string;
38
+ durationMs: number;
39
+ };
40
+
41
+ interface Deps {
42
+ audio: RecorderAudio;
43
+ send(file: SendFile): Promise<'sent' | 'queued'>;
44
+ newId(): string;
45
+ ensurePermission?: () => Promise<Permission>;
46
+ diag?: { log(event: string, fields?: Record<string, unknown>): void };
47
+ now?: () => number;
48
+ schedule?: (fn: () => void, ms: number) => () => void;
49
+ }
50
+
51
+ const defaultSchedule = (fn: () => void, ms: number) => {
52
+ const handle = setTimeout(fn, ms);
53
+ return () => clearTimeout(handle);
54
+ };
55
+
56
+ export function createRecorder(deps: Deps) {
57
+ const now = deps.now ?? Date.now;
58
+ const schedule = deps.schedule ?? defaultSchedule;
59
+ const log = (event: string, fields?: Record<string, unknown>) => deps.diag?.log(event, fields);
60
+ let state: RecorderState = { phase: 'idle' };
61
+ const listeners = new Set<(s: RecorderState) => void>();
62
+ let starting = false;
63
+ let startedAt = 0;
64
+ let cancelAutostop: (() => void) | null = null;
65
+ let permission: Permission | 'unknown' = 'unknown';
66
+
67
+ const set = (next: RecorderState) => {
68
+ state = next;
69
+ listeners.forEach((l) => l(state));
70
+ };
71
+
72
+ async function go(options: GoOptions = {}): Promise<void> {
73
+ if (starting || state.phase === 'recording' || state.phase === 'uploading') return;
74
+ starting = true;
75
+ try {
76
+ if (deps.ensurePermission) {
77
+ try {
78
+ permission = await deps.ensurePermission();
79
+ } catch (e) {
80
+ const error = e instanceof Error ? e.message : String(e);
81
+ log('record.error', { stage: 'permission', error });
82
+ set({ phase: 'idle', error: STRINGS.micStartFailed });
83
+ return;
84
+ }
85
+ if (permission === 'denied') {
86
+ log('record.denied', {});
87
+ state = { phase: 'idle', permission: 'denied' };
88
+ listeners.forEach((l) => l(state));
89
+ return;
90
+ }
91
+ }
92
+ const id = deps.newId();
93
+ try {
94
+ await deps.audio.start({
95
+ onLevel: (db) => {
96
+ if (state.phase === 'recording') set({ ...state, levelDb: db });
97
+ },
98
+ });
99
+ } catch (e) {
100
+ const error = e instanceof Error ? e.message : String(e);
101
+ log('record.error', { id, error });
102
+ set({ phase: 'idle', error });
103
+ return;
104
+ }
105
+ startedAt = now();
106
+ log('record.start', { id, permission });
107
+ set({ phase: 'recording', noteId: id, permission: permission === 'unknown' ? undefined : permission });
108
+ if (options.autostopSeconds) {
109
+ log('record.autostop.scheduled', { id, seconds: options.autostopSeconds });
110
+ cancelAutostop = schedule(() => { void stop(); }, options.autostopSeconds * 1000);
111
+ }
112
+ } finally {
113
+ starting = false;
114
+ }
115
+ }
116
+
117
+ async function stop(): Promise<StoppedRecording | null> {
118
+ if (state.phase !== 'recording') return null;
119
+ cancelAutostop?.();
120
+ cancelAutostop = null;
121
+ const id = state.noteId!;
122
+ let file: StoppedRecording;
123
+ try {
124
+ file = await deps.audio.stop();
125
+ } catch (e) {
126
+ const error = e instanceof Error ? e.message : String(e);
127
+ log('record.error', { id, error, stage: 'stop' });
128
+ set({ phase: 'idle', error });
129
+ return null;
130
+ }
131
+ const elapsedMs = now() - startedAt;
132
+ log('record.stop', {
133
+ id, uri: file.uri, bytes: file.bytes, durationMs: file.durationMs, elapsedMs, peakDb: file.peakDb, rmsDb: file.rmsDb,
134
+ });
135
+ const silent = file.peakDb !== undefined && isSilent({ peakDb: file.peakDb, samples: 1 });
136
+ if (silent) log('record.no-audio', { id, peakDb: file.peakDb });
137
+ set({ phase: 'uploading', noteId: id, permission: state.permission });
138
+ let outcome: 'sent' | 'queued';
139
+ try {
140
+ outcome = await deps.send({ id, uri: file.uri, durationMs: file.durationMs });
141
+ } catch (e) {
142
+ log('record.send-error', { id, error: e instanceof Error ? e.message : String(e) });
143
+ outcome = 'queued';
144
+ }
145
+ set({ phase: outcome, noteId: id, permission: state.permission, ...(silent ? { warning: 'no-audio' as const } : {}) });
146
+ return file;
147
+ }
148
+
149
+ return {
150
+ getState: () => state,
151
+ subscribe(listener: (s: RecorderState) => void) {
152
+ listeners.add(listener);
153
+ return () => { listeners.delete(listener); };
154
+ },
155
+ go,
156
+ stop,
157
+ /** The system took the mic (call, Siri, route loss): finalize and queue what we have. */
158
+ async interrupt(reason: string) {
159
+ if (state.phase !== 'recording') return;
160
+ log('record.interrupted', { id: state.noteId, reason });
161
+ await stop();
162
+ },
163
+ };
164
+ }