@startsimpli/integrations 0.2.80 → 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.
package/README.md CHANGED
@@ -184,7 +184,7 @@ the screens need the OPTIONAL peers `react-native`, `react-native-safe-area-cont
184
184
 
185
185
  1. Copy `~/Repos/tandem-ios` to `<foundry>-ios`. Change `app.json` (`name`, `slug`, `scheme`, `ios.bundleIdentifier`, microphone strings), `src/config.ts` (the Foundry's tenant URL; central auth is `https://api.startsimpli.com`), `src/strings.ts` and the theme in `App.tsx`.
186
186
  2. `pnpm install`. It depends on published `@startsimpli/{auth,integrations,ui-native,utils}`, so nothing is linked.
187
- 3. Keep the recording files as they are (`src/recorder*.ts`, `src/native.ts`, `modules/tandem-audio-session`): they are not packaged yet (bd startsim-ij1lw.9).
187
+ 3. The recording path is in this package (`native/recording`: `createRecorder`, `createRecorderAudio`, `createPermissionFlow`, `recoverOrphans`, `createDeepLink`, `createDiagnostics`, `createSession`, `createNotes`, level helpers). The shell keeps only the device bindings, injected through `AudioDriver`, `SessionInspector`, `PermissionsApi` and `RecordingFile`: `src/native.ts` (expo-audio, expo-file-system) and `modules/tandem-audio-session` (bd startsim-ij1lw.9). `createDeepLink({ scheme })`, `createDiagnostics({ tag })` and `createSession({ app })` default to the Tandem Go values.
188
188
  4. `src/services.ts` builds `createNativeVoiceApi` + `createVoiceNotesController`; `App.tsx` renders `<NotesShell go={<MainScreen .../>} controller={s.notesController} />`.
189
189
  5. Check without a login: launch with `-tgFakeNotes list` (or a note id such as `n1`) to see the screens over `createFakeVoiceApi`.
190
190
  6. `npx expo prebuild --platform ios`, then `npx expo run:ios --configuration Release` (Hermes). Signing and device install are per-Apple-team, see the template README.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@startsimpli/integrations",
3
- "version": "0.2.80",
3
+ "version": "0.2.81",
4
4
  "description": "Provider-agnostic types, API clients, hooks, and UI primitives for email + calendar integrations across StartSimpli apps, plus foundry customer email (subpath ./comms).",
5
5
  "license": "MIT",
6
6
  "homepage": "https://startsimpli.com",
@@ -50,6 +50,8 @@
50
50
  "react-native": ">=0.74.0",
51
51
  "@startsimpli/ui-native": ">=0.1.0",
52
52
  "react-native-safe-area-context": ">=4.0.0",
53
+ "@startsimpli/auth": "^0.4.47",
54
+ "@startsimpli/utils": "^0.4.15",
53
55
  "@startsimpli/ui": "^0.4.167"
54
56
  },
55
57
  "peerDependenciesMeta": {
@@ -73,6 +75,12 @@
73
75
  },
74
76
  "react-native-safe-area-context": {
75
77
  "optional": true
78
+ },
79
+ "@startsimpli/auth": {
80
+ "optional": true
81
+ },
82
+ "@startsimpli/utils": {
83
+ "optional": true
76
84
  }
77
85
  },
78
86
  "devDependencies": {
@@ -90,9 +98,11 @@
90
98
  "vitest": "^3.0.0",
91
99
  "react-native": "0.85.3",
92
100
  "react-native-safe-area-context": "~5.7.0",
93
- "@startsimpli/ui-native": "0.1.2",
94
101
  "@startsimpli/llm": "0.4.28",
95
- "@startsimpli/ui": "0.4.167"
102
+ "@startsimpli/ui": "0.4.167",
103
+ "@startsimpli/ui-native": "0.1.3",
104
+ "@startsimpli/utils": "0.4.15",
105
+ "@startsimpli/auth": "0.4.47"
96
106
  },
97
107
  "scripts": {
98
108
  "type-check": "tsc --noEmit && tsc --noEmit -p tsconfig.native.json",
@@ -14,6 +14,7 @@ export { NotesListScreen, type NotesListScreenProps } from './components/NotesLi
14
14
  export { NoteDetailScreen, type NoteDetailScreenProps } from './components/NoteDetailScreen';
15
15
  export { NotesShell, type NotesShellProps } from './components/NotesShell';
16
16
  export { FoundryTabsShell, type FoundryTab, type FoundryTabsShellProps, type TabContext } from './components/FoundryTabsShell';
17
+ export * from './recording';
17
18
  export * from './shell/navigator';
18
19
  export * from './shell/overflow';
19
20
  export * from './corpus/api';
@@ -0,0 +1,92 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createDeepLink } from '../deeplink';
3
+
4
+ function setup(phase: string = 'idle') {
5
+ const go = vi.fn().mockResolvedValue(undefined);
6
+ const link = createDeepLink({ getPhase: () => phase, go, log: vi.fn() });
7
+ return { link, go };
8
+ }
9
+
10
+ describe('deep link tandemgo://record', () => {
11
+ it('waits for the session, then starts recording once', async () => {
12
+ const { link, go } = setup();
13
+ link.handle('tandemgo://record');
14
+ expect(go).not.toHaveBeenCalled();
15
+ await link.sessionReady();
16
+ expect(go).toHaveBeenCalledTimes(1);
17
+ await link.sessionReady();
18
+ expect(go).toHaveBeenCalledTimes(1);
19
+ });
20
+
21
+ it('starts immediately when the session is already ready', async () => {
22
+ const { link, go } = setup();
23
+ await link.sessionReady();
24
+ link.handle('tandemgo://record');
25
+ await Promise.resolve();
26
+ expect(go).toHaveBeenCalledTimes(1);
27
+ });
28
+
29
+ it('is ignored while already recording', async () => {
30
+ const { link, go } = setup('recording');
31
+ await link.sessionReady();
32
+ link.handle('tandemgo://record');
33
+ expect(go).not.toHaveBeenCalled();
34
+ });
35
+
36
+ it('ignores other urls', async () => {
37
+ const { link, go } = setup();
38
+ await link.sessionReady();
39
+ link.handle('tandemgo://settings');
40
+ link.handle('https://example.com/record');
41
+ expect(go).not.toHaveBeenCalled();
42
+ });
43
+
44
+ it('sign-out forgets readiness', async () => {
45
+ const { link, go } = setup();
46
+ await link.sessionReady();
47
+ link.sessionLost();
48
+ link.handle('tandemgo://record');
49
+ expect(go).not.toHaveBeenCalled();
50
+ });
51
+ });
52
+
53
+ describe('deep link autostop test hook', () => {
54
+ it('tandemgo://record?autostop=7 starts with a 7s autostop', async () => {
55
+ const { link, go } = setup();
56
+ await link.sessionReady();
57
+ link.handle('tandemgo://record?autostop=7');
58
+ await Promise.resolve();
59
+ expect(go).toHaveBeenCalledWith({ autostopSeconds: 7 });
60
+ });
61
+
62
+ it('plain record has no autostop', async () => {
63
+ const { link, go } = setup();
64
+ await link.sessionReady();
65
+ link.handle('tandemgo://record');
66
+ await Promise.resolve();
67
+ expect(go).toHaveBeenCalledWith({});
68
+ });
69
+
70
+ it.each(['autostop=abc', 'autostop=-3', 'autostop=0'])('ignores a bad value (%s) and stays manual', async (q) => {
71
+ const { link, go } = setup();
72
+ await link.sessionReady();
73
+ link.handle(`tandemgo://record?${q}`);
74
+ await Promise.resolve();
75
+ expect(go).toHaveBeenCalledWith({});
76
+ });
77
+
78
+ it('a cold-start autostop link keeps its seconds until the session is ready', async () => {
79
+ const { link, go } = setup();
80
+ link.handle('tandemgo://record?autostop=12');
81
+ await link.sessionReady();
82
+ expect(go).toHaveBeenCalledWith({ autostopSeconds: 12 });
83
+ });
84
+
85
+ it('logs every link it receives, including ignored ones', async () => {
86
+ const log = vi.fn();
87
+ const link = createDeepLink({ getPhase: () => 'recording', go: vi.fn(), log });
88
+ await link.sessionReady();
89
+ link.handle('tandemgo://record');
90
+ expect(log).toHaveBeenCalledWith('deeplink', expect.objectContaining({ url: 'tandemgo://record', action: 'ignored-recording' }));
91
+ });
92
+ });
@@ -0,0 +1,80 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createDiagnostics } from '../diagnostics';
3
+
4
+ describe('diagnostics', () => {
5
+ it('records structured entries and mirrors each as ONE greppable console line', () => {
6
+ const sink = vi.fn();
7
+ let t = 100;
8
+ const d = createDiagnostics({ sink, now: () => t++ });
9
+ d.log('record.start', { id: 'n1', sampleRate: 44100 });
10
+ expect(d.entries()).toEqual([{ t: 100, event: 'record.start', id: 'n1', sampleRate: 44100 }]);
11
+ const line = sink.mock.calls[0][0] as string;
12
+ expect(line.startsWith('[tandemgo] ')).toBe(true);
13
+ expect(JSON.parse(line.replace('[tandemgo] ', ''))).toEqual(d.entries()[0]);
14
+ });
15
+
16
+ it('keeps only the newest N entries', () => {
17
+ const d = createDiagnostics({ sink: vi.fn(), max: 3 });
18
+ for (let i = 0; i < 5; i++) d.log('e', { i });
19
+ expect(d.entries().map((e) => e.i)).toEqual([2, 3, 4]);
20
+ });
21
+
22
+ it('notifies subscribers and persists through the injected store', async () => {
23
+ let saved = '';
24
+ const d = createDiagnostics({ sink: vi.fn(), persist: async (v) => { saved = v; } });
25
+ const seen = vi.fn();
26
+ d.subscribe(seen);
27
+ d.log('x', {});
28
+ expect(seen).toHaveBeenCalledTimes(1);
29
+ await d.flush();
30
+ expect(JSON.parse(saved)).toHaveLength(1);
31
+ });
32
+
33
+ it('never throws from a broken sink or store', async () => {
34
+ const d = createDiagnostics({ sink: () => { throw new Error('x'); }, persist: async () => { throw new Error('y'); } });
35
+ expect(() => d.log('x', {})).not.toThrow();
36
+ await expect(d.flush()).resolves.toBeUndefined();
37
+ });
38
+
39
+ it('never logs secrets: password/token/authorization fields are redacted', () => {
40
+ const d = createDiagnostics({ sink: vi.fn() });
41
+ d.log('x', { password: 'p', accessToken: 'a', Authorization: 'Bearer z', ok: 1 });
42
+ expect(JSON.stringify(d.entries())).not.toMatch(/Bearer z|"p"|"a"/);
43
+ expect(d.entries()[0].ok).toBe(1);
44
+ });
45
+
46
+ it('keeps entries from earlier launches: the persisted log is loaded before the first write', async () => {
47
+ const writes: string[] = [];
48
+ const d = createDiagnostics({
49
+ sink: vi.fn(),
50
+ now: () => 2,
51
+ load: async () => JSON.stringify([{ t: 1, event: 'old' }]),
52
+ persist: async (v) => { writes.push(v); },
53
+ });
54
+ d.log('new');
55
+ await d.flush();
56
+ expect(JSON.parse(writes[writes.length - 1]).map((e: { event: string }) => e.event)).toEqual(['old', 'new']);
57
+ expect(d.entries().map((e) => e.event)).toEqual(['old', 'new']);
58
+ });
59
+
60
+ it('a missing, corrupt or failing persisted log never breaks logging', async () => {
61
+ for (const load of [async () => null, async () => 'not json', async () => { throw new Error('io'); }]) {
62
+ const writes: string[] = [];
63
+ const d = createDiagnostics({ sink: vi.fn(), load, persist: async (v) => { writes.push(v); } });
64
+ d.log('x');
65
+ await d.flush();
66
+ expect(JSON.parse(writes[writes.length - 1])).toHaveLength(1);
67
+ }
68
+ });
69
+
70
+ it('respects max across old and new entries', async () => {
71
+ const d = createDiagnostics({
72
+ sink: vi.fn(), max: 3,
73
+ load: async () => JSON.stringify([{ t: 1, event: 'a' }, { t: 2, event: 'b' }, { t: 3, event: 'c' }]),
74
+ persist: async () => undefined,
75
+ });
76
+ d.log('d');
77
+ await d.flush();
78
+ expect(d.entries().map((e) => e.event)).toEqual(['b', 'c', 'd']);
79
+ });
80
+ });
@@ -0,0 +1,10 @@
1
+ /** jest-expo's FormData is Node's; the device has React Native's. A fake that records appended parts. */
2
+ export class FakeForm {
3
+ parts: Array<{ fieldName: string; string?: string; uri?: string; type?: string; name?: string }> = [];
4
+ append(name: string, value: unknown, filename?: string) {
5
+ if (filename !== undefined) this.parts.push({ fieldName: name, name: filename, blob: value } as never);
6
+ else if (typeof value === 'string') this.parts.push({ fieldName: name, string: value });
7
+ else this.parts.push({ fieldName: name, ...(value as object) });
8
+ }
9
+ getParts() { return this.parts; }
10
+ }
@@ -0,0 +1,47 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { createUploadQueue } from '@startsimpli/utils';
3
+ import { createNotes } from '../notes';
4
+ import { createRecorder } from '../recorder';
5
+ import { FakeForm } from './fakeForm';
6
+
7
+ // Recorder + real shared queue + notes.upload with a flaky network: the same
8
+ // noteId is sent on every attempt, the file is deleted once, after the 2xx.
9
+ describe('offline then online', () => {
10
+ it('queues while offline and sends exactly once with the same noteId', async () => {
11
+ let online = false;
12
+ const seenIds: string[] = [];
13
+ const authorizedFetch = vi.fn(async (_url: string, init: { body: { getParts(): Array<{ fieldName: string; string?: string }> } }) => {
14
+ if (!online) throw new TypeError('Network request failed');
15
+ seenIds.push(init.body.getParts().find((p) => p.fieldName === 'noteId')!.string!);
16
+ return { ok: true, status: 202, json: async () => ({}) } as Response;
17
+ });
18
+ const notes = createNotes({ tandemUrl: 'http://t', authorizedFetch: authorizedFetch as never, createForm: () => new FakeForm() as never });
19
+ let saved: string | null = null;
20
+ const removed: string[] = [];
21
+ let now = 0;
22
+ const queue = createUploadQueue({
23
+ store: { read: async () => saved, write: async (v) => { saved = v; } },
24
+ upload: (job) => notes.upload({ id: job.id, uri: job.uri, durationMs: job.durationMs ?? 0 }),
25
+ removeFile: async (job) => { removed.push(job.uri); },
26
+ now: () => now,
27
+ });
28
+ const recorder = createRecorder({
29
+ audio: { start: async () => undefined, stop: async () => ({ uri: 'file:///d/x.m4a', durationMs: 900 }) },
30
+ send: (file) => queue.enqueue(file),
31
+ newId: () => 'fixed-note-id',
32
+ });
33
+
34
+ await recorder.go();
35
+ await recorder.stop();
36
+ expect(recorder.getState().phase).toBe('queued');
37
+ expect(removed).toEqual([]);
38
+
39
+ online = true;
40
+ now += 60_000;
41
+ await queue.drain();
42
+ await queue.drain();
43
+ expect(seenIds).toEqual(['fixed-note-id']);
44
+ expect(removed).toEqual(['file:///d/x.m4a']);
45
+ expect(await queue.pending()).toEqual([]);
46
+ });
47
+ });
@@ -0,0 +1,38 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createLevelTracker, meterFraction, NO_AUDIO_FLOOR_DB, isSilent } from '../levels';
3
+
4
+ describe('levels', () => {
5
+ it('tracks peak and RMS (RMS averaged in linear power, not in dB)', () => {
6
+ const t = createLevelTracker();
7
+ [-60, -20, -10].forEach((db) => t.push(db));
8
+ const s = t.summary();
9
+ expect(s.peakDb).toBe(-10);
10
+ const lin = (db: number) => 10 ** (db / 10);
11
+ const expected = 10 * Math.log10((lin(-60) + lin(-20) + lin(-10)) / 3);
12
+ expect(s.rmsDb).toBeCloseTo(expected, 5);
13
+ expect(s.samples).toBe(3);
14
+ });
15
+
16
+ it('no samples = floor values, flagged silent', () => {
17
+ const s = createLevelTracker().summary();
18
+ expect(s.samples).toBe(0);
19
+ expect(isSilent(s)).toBe(true);
20
+ });
21
+
22
+ it('silent when the peak never rises above the floor; speech is not silent', () => {
23
+ const quiet = createLevelTracker();
24
+ [-80, -70, NO_AUDIO_FLOOR_DB - 1].forEach((d) => quiet.push(d));
25
+ expect(isSilent(quiet.summary())).toBe(true);
26
+ const talk = createLevelTracker();
27
+ [-80, -25, -40].forEach((d) => talk.push(d));
28
+ expect(isSilent(talk.summary())).toBe(false);
29
+ });
30
+
31
+ it('meterFraction maps dB to 0..1 and clamps', () => {
32
+ expect(meterFraction(0)).toBe(1);
33
+ expect(meterFraction(-160)).toBe(0);
34
+ expect(meterFraction(-200)).toBe(0);
35
+ expect(meterFraction(10)).toBe(1);
36
+ expect(meterFraction(-30)).toBeGreaterThan(meterFraction(-50));
37
+ });
38
+ });
@@ -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
+ });